diff --git a/Gulpfile.ts b/Gulpfile.ts index 24ff1f3f3c9fe..b728048322646 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -87,7 +87,7 @@ function possiblyQuote(cmd: string) { } let useDebugMode = true; -let host = cmdLineOptions["host"]; +let host = cmdLineOptions.host; // Constants const compilerDirectory = "src/compiler/"; @@ -180,6 +180,23 @@ const libraryTargets = librarySourceMap.map(function(f) { return path.join(builtLocalDirectory, f.target); }); +/** + * .lcg file is what localization team uses to know what messages to localize. + * The file is always generated in 'enu\diagnosticMessages.generated.json.lcg' + */ +const generatedLCGFile = path.join(builtLocalDirectory, "enu", "diagnosticMessages.generated.json.lcg"); + +/** + * The localization target produces the two following transformations: + * 1. 'src\loc\lcl\\diagnosticMessages.generated.json.lcl' => 'built\local\\diagnosticMessages.generated.json' + * convert localized resources into a .json file the compiler can understand + * 2. 'src\compiler\diagnosticMessages.generated.json' => 'built\local\ENU\diagnosticMessages.generated.json.lcg' + * generate the lcg file (source of messages to localize) from the diagnosticMessages.generated.json + */ +const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-BR", "ru", "tr", "zh-CN", "zh-TW"].map(function (f) { + return path.join(builtLocalDirectory, f, "diagnosticMessages.generated.json"); +}).concat(generatedLCGFile); + for (const i in libraryTargets) { const entry = librarySourceMap[i]; const target = libraryTargets[i]; @@ -398,7 +415,6 @@ gulp.task(generateLocalizedDiagnosticMessagesJs, /*help*/ false, [], () => { }); // Localize diagnostics -const generatedLCGFile = path.join(builtLocalDirectory, "enu", "diagnosticMessages.generated.json.lcg"); gulp.task(generatedLCGFile, [generateLocalizedDiagnosticMessagesJs, diagnosticInfoMapTs], (done) => { if (fs.existsSync(builtLocalDirectory) && needsUpdate(generatedDiagnosticMessagesJSON, generatedLCGFile)) { exec(host, [generateLocalizedDiagnosticMessagesJs, lclDirectory, builtLocalDirectory, generatedDiagnosticMessagesJSON], done, done); @@ -576,8 +592,7 @@ gulp.task("dontUseDebugMode", /*help*/ false, [], (done) => { useDebugMode = fal gulp.task("VerifyLKG", /*help*/ false, [], () => { const expectedFiles = [builtLocalCompiler, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, typingsInstallerJs, cancellationTokenJs].concat(libraryTargets); const missingFiles = expectedFiles. - concat(fs.readdirSync(lclDirectory).map(function (d) { return path.join(builtLocalDirectory, d, "diagnosticMessages.generated.json"); })). - concat(generatedLCGFile). + concat(localizationTargets). filter(f => !fs.existsSync(f)); if (missingFiles.length > 0) { throw new Error("Cannot replace the LKG unless all built targets are present in directory " + builtLocalDirectory + @@ -636,15 +651,15 @@ function restoreSavedNodeEnv() { } function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: (e?: any) => void) { - const lintFlag = cmdLineOptions["lint"]; + const lintFlag = cmdLineOptions.lint; cleanTestDirs((err) => { if (err) { console.error(err); failWithStatus(err, 1); } - let testTimeout = cmdLineOptions["timeout"]; - const debug = cmdLineOptions["debug"]; - const inspect = cmdLineOptions["inspect"]; - const tests = cmdLineOptions["tests"]; - const light = cmdLineOptions["light"]; - const stackTraceLimit = cmdLineOptions["stackTraceLimit"]; + let testTimeout = cmdLineOptions.timeout; + const debug = cmdLineOptions.debug; + const inspect = cmdLineOptions.inspect; + const tests = cmdLineOptions.tests; + const light = cmdLineOptions.light; + const stackTraceLimit = cmdLineOptions.stackTraceLimit; const testConfigFile = "test.config"; if (fs.existsSync(testConfigFile)) { fs.unlinkSync(testConfigFile); @@ -660,7 +675,7 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: } while (fs.existsSync(taskConfigsFolder)); fs.mkdirSync(taskConfigsFolder); - workerCount = cmdLineOptions["workers"]; + workerCount = cmdLineOptions.workers; } if (tests || light || taskConfigsFolder) { @@ -671,8 +686,8 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: testTimeout = 400000; } - const colors = cmdLineOptions["colors"]; - const reporter = cmdLineOptions["reporter"] || defaultReporter; + const colors = cmdLineOptions.colors; + const reporter = cmdLineOptions.reporter || defaultReporter; // timeout normally isn"t necessary but Travis-CI has been timing out on compiler baselines occasionally // default timeout is 2sec which really should be enough, but maybe we just need a small amount longer @@ -860,7 +875,7 @@ function cleanTestDirs(done: (e?: any) => void) { // used to pass data from jake command line directly to run.js function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?: string, workerCount?: number, stackTraceLimit?: string) { - const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light, workerCount, stackTraceLimit, taskConfigsFolder, noColor: !cmdLineOptions["colors"] }); + const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light, workerCount, stackTraceLimit, taskConfigsFolder, noColor: !cmdLineOptions.colors }); console.log("Running tests with config: " + testConfigContents); fs.writeFileSync("test.config", testConfigContents); } @@ -870,8 +885,8 @@ gulp.task("runtests-browser", "Runs the tests using the built run.js file like ' cleanTestDirs((err) => { if (err) { console.error(err); done(err); process.exit(1); } host = "node"; - const tests = cmdLineOptions["tests"]; - const light = cmdLineOptions["light"]; + const tests = cmdLineOptions.tests; + const light = cmdLineOptions.light; const testConfigFile = "test.config"; if (fs.existsSync(testConfigFile)) { fs.unlinkSync(testConfigFile); @@ -881,8 +896,8 @@ gulp.task("runtests-browser", "Runs the tests using the built run.js file like ' } const args = [nodeServerOutFile]; - if (cmdLineOptions["browser"]) { - args.push(cmdLineOptions["browser"]); + if (cmdLineOptions.browser) { + args.push(cmdLineOptions.browser); } if (tests) { args.push(JSON.stringify(tests)); @@ -892,13 +907,13 @@ gulp.task("runtests-browser", "Runs the tests using the built run.js file like ' }); gulp.task("generate-code-coverage", "Generates code coverage data via istanbul", ["tests"], (done) => { - const testTimeout = cmdLineOptions["timeout"]; + const testTimeout = cmdLineOptions.timeout; exec("istanbul", ["cover", "node_modules/mocha/bin/_mocha", "--", "-R", "min", "-t", testTimeout.toString(), run], done, done); }); function getDiffTool() { - const program = process.env["DIFF"]; + const program = process.env.DIFF; if (!program) { console.error("Add the 'DIFF' environment variable to the path of the program you want to use."); process.exit(1); @@ -1019,7 +1034,7 @@ gulp.task(instrumenterJsPath, /*help*/ false, [servicesFile], () => { }); gulp.task("tsc-instrumented", "Builds an instrumented tsc.js - run with --test=[testname]", ["local", loggedIOJsPath, instrumenterJsPath, servicesFile], (done) => { - const test = cmdLineOptions["tests"] || "iocapture"; + const test = cmdLineOptions.tests || "iocapture"; exec(host, [instrumenterJsPath, "record", test, builtLocalCompiler], done, done); }); @@ -1088,7 +1103,7 @@ function spawnLintWorker(files: {path: string}[], callback: (failures: number) = gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => { if (fold.isTravis()) console.log(fold.start("lint")); - const fileMatcher = cmdLineOptions["files"]; + const fileMatcher = cmdLineOptions.files; const files = fileMatcher ? `src/**/${fileMatcher}` : "Gulpfile.ts 'scripts/generateLocalizedDiagnosticMessages.ts' 'scripts/tslint/**/*.ts' 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'"; diff --git a/Jakefile.js b/Jakefile.js index 0b3659e205116..06f13262a2841 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -154,6 +154,7 @@ var harnessSources = harnessCoreSources.concat([ "symbolWalker.ts", "languageService.ts", "publicApi.ts", + "hostNewLineSupport.ts", ].map(function (f) { return path.join(unittestsDirectory, f); })).concat([ @@ -238,6 +239,23 @@ var libraryTargets = librarySourceMap.map(function (f) { return path.join(builtLocalDirectory, f.target); }); +/** + * .lcg file is what localization team uses to know what messages to localize. + * The file is always generated in 'enu\diagnosticMessages.generated.json.lcg' + */ +var generatedLCGFile = path.join(builtLocalDirectory, "enu", "diagnosticMessages.generated.json.lcg"); + +/** + * The localization target produces the two following transformations: + * 1. 'src\loc\lcl\\diagnosticMessages.generated.json.lcl' => 'built\local\\diagnosticMessages.generated.json' + * convert localized resources into a .json file the compiler can understand + * 2. 'src\compiler\diagnosticMessages.generated.json' => 'built\local\ENU\diagnosticMessages.generated.json.lcg' + * generate the lcg file (source of messages to localize) from the diagnosticMessages.generated.json + */ +var localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-BR", "ru", "tr", "zh-CN", "zh-TW"].map(function (f) { + return path.join(builtLocalDirectory, f); +}).concat(path.dirname(generatedLCGFile)); + // Prepends the contents of prefixFile to destinationFile function prependFile(prefixFile, destinationFile) { if (!fs.existsSync(prefixFile)) { @@ -443,7 +461,6 @@ compileFile(generateLocalizedDiagnosticMessagesJs, /*useBuiltCompiler*/ false, { noOutFile: true, types: ["node", "xml2js"] }); // Localize diagnostics -var generatedLCGFile = path.join(builtLocalDirectory, "enu", "diagnosticMessages.generated.json.lcg"); file(generatedLCGFile, [generateLocalizedDiagnosticMessagesJs, diagnosticInfoMapTs, generatedDiagnosticMessagesJSON], function () { var cmd = host + " " + generateLocalizedDiagnosticMessagesJs + " " + lclDirectory + " " + builtLocalDirectory + " " + generatedDiagnosticMessagesJSON; console.log(cmd); @@ -735,8 +752,7 @@ 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, buildProtocolDts, watchGuardFile]. concat(libraryTargets). - concat(fs.readdirSync(lclDirectory).map(function (d) { return path.join(builtLocalDirectory, d) })). - concat(path.dirname(generatedLCGFile)); + concat(localizationTargets); var missingFiles = expectedFiles.filter(function (f) { return !fs.existsSync(f); }); diff --git a/lib/csy/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json similarity index 99% rename from lib/csy/diagnosticMessages.generated.json rename to lib/cs/diagnosticMessages.generated.json index 948ce696aff77..ad386bb38bcfb 100644 --- a/lib/csy/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Výraz yield je povolený jenom v těle generátoru.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "K abstraktní metodě {0} ve třídě {1} nejde získat přístup prostřednictvím výrazu super.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Abstraktní metody se můžou vyskytovat jenom v abstraktní třídě.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "K abstraktní vlastnosti {0} ve třídě {1} nelze získat přístup v konstruktoru.", "Accessibility_modifier_already_seen_1028": "Modifikátor dostupnosti se už jednou vyskytl.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Přístupové objekty jsou dostupné, jenom když je cílem ECMAScript 5 a vyšší verze.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Člen objektu nemůže být deklarovaný jako nepovinný.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Signatura přetížení nemůže být deklarovaný jako generátor.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Unární výraz s operátorem {0} se na levé straně výrazu umocnění nepovoluje. Zvažte možnost uzavření výrazu do závorek.", + "Annotate_with_type_from_JSDoc_95009": "Přidat poznámku s typem z JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Přidat poznámky s typy z JSDoc", "Argument_expression_expected_1135": "Očekává se výraz argumentu.", "Argument_for_0_option_must_be_Colon_1_6046": "Argument možnosti {0} musí být {1}.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Argument typu {0} nejde přiřadit k parametru typu {1}.", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "Očekává se binární číslice.", "Binding_element_0_implicitly_has_an_1_type_7031": "Element vazby {0} má implicitně typ {1}.", "Block_scoped_variable_0_used_before_its_declaration_2448": "Proměnná bloku {0} se používá před vlastní deklarací.", + "Call_decorator_expression_90028": "Výraz pro volání dekoratéru", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Signatura volání s chybějící anotací návratového typu má implicitně návratový typ any.", "Call_target_does_not_contain_any_signatures_2346": "Cíl volání neobsahuje žádné signatury.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "K {0}.{1} nelze získat přístup, protože {0} je typ, nikoli názvový prostor. Chtěli jste načíst typ vlastnosti {1} v {0} pomocí {0}[{1}]?", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "Třída {0} nesprávně rozšiřuje základní třídu {1}.", "Class_0_incorrectly_implements_interface_1_2420": "Třída {0} nesprávně implementuje rozhraní {1}.", "Class_0_used_before_its_declaration_2449": "Třída {0} se používá dříve, než se deklaruje.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklarace tříd nemůžou obsahovat více než jednu značku @augments nebo @extends.", "Class_name_cannot_be_0_2414": "Třída nemůže mít název {0}.", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Statická strana třídy {0} nesprávně rozšiřuje statickou stranu základní třídy {1}.", "Classes_can_only_extend_a_single_class_1174": "Třídy můžou rozšířit jenom jednu třídu.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "V typu {0} chybí signatura indexu.", "Index_signatures_are_incompatible_2330": "Signatury indexu jsou nekompatibilní.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Jednotlivé deklarace ve sloučené deklaraci {0} musí být všechny exportované nebo všechny místní.", + "Infer_parameter_types_from_usage_95012": "Odvodit typy parametrů z používání", + "Infer_type_of_0_from_usage_95011": "Odvodit typ {0} z používání", "Initialize_property_0_in_the_constructor_90020": "Inicializovat vlastnost {0} v konstruktoru", "Initialize_static_property_0_90021": "Inicializovat statickou vlastnost {0}", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicializátor instance členské proměnné {0} nemůže odkazovat na identifikátor {1} deklarovaný v konstruktoru.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "Neplatné použití {0} ve striktním režimu", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Neplatná hodnota pro jsxFactory. {0} není platný identifikátor nebo kvalifikovaný název.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Neplatná hodnota --reactNamespace. {0} není platný identifikátor.", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "Značka JSDoc @augments {0} neodpovídá klauzuli extends {1}.", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "Značka JSDoc @augments není připojená k deklaraci třídy.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Značka JSDoc @{0} {1} neodpovídá klauzuli extends {2}.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Značka JSDoc @{0} není připojená k třídě.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Značka JSDoc @param má název {0}, ale žádný parametr s tímto názvem neexistuje.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Značka JSDoc @typedef by měla mít anotaci typu nebo by za ní měla následovat značka @property nebo @member.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc se můžou používat jenom v dokumentačních komentářích.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterovaných elementů yield* musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu yield v asynchronním generátoru musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu {0} má cyklické omezení.", + "Type_parameter_0_has_a_circular_default_2716": "Parametr typu {0} má cyklickou výchozí hodnotu.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Parametr typu {0} signatury konstruktoru z exportovaného rozhraní má nebo používá privátní název {1}.", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Parametr typu {0} exportované třídy má nebo používá privátní název {1}.", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "Sledovat vstupní soubory", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nejde přejmenovat elementy definované ve standardní knihovně TypeScriptu.", "You_cannot_rename_this_element_8000": "Tento element nejde přejmenovat.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Objekt {0} přijímá málo argumentů k tomu, aby se dal použít jako dekoratér. Nechtěli jste ho nejprve volat a napsat @{0}()?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Položka {0} je zadána dvakrát. Atribut s názvem {0} se přepíše.", "_0_can_only_be_used_in_a_ts_file_8009": "{0} se dá použít jenom v souboru .ts.", "_0_expected_1005": "Očekával se: {0}.", diff --git a/lib/deu/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json similarity index 98% rename from lib/deu/diagnosticMessages.generated.json rename to lib/de/diagnosticMessages.generated.json index ef305bb2b4625..60b164c65a695 100644 --- a/lib/deu/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -246,6 +246,7 @@ "Declare_method_0_90023": "Methode \"{0}\" deklarieren.", "Declare_property_0_90016": "Eigenschaft \"{0}\" deklarieren.", "Declare_static_method_0_90024": "Statische Methode \"{0}\" deklarieren.", + "Declare_static_property_0_90027": "Deklarieren Sie die statische Eigenschaft \"{0}\".", "Decorators_are_not_valid_here_1206": "Decorators sind hier ungültig.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Decorators dürfen nicht auf mehrere get-/set-Zugriffsmethoden mit dem gleichen Namen angewendet werden.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Der Standardexport des Moduls besitzt oder verwendet den privaten Namen \"{0}\".", @@ -293,6 +294,7 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Geben Sie eine einzelne Datei mit Quellzuordnungen anstelle einer separaten Datei aus.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Geben Sie die Quelle zusammen mit den Quellzuordnungen innerhalb einer einzelnen Datei aus; hierfür muss \"--inlineSourceMap\" oder \"--sourceMap\" festgelegt sein.", "Enable_all_strict_type_checking_options_6180": "Aktivieren Sie alle strengen Typüberprüfungsoptionen.", + "Enable_strict_checking_of_function_types_6186": "Aktivieren Sie die strenge Überprüfung für Funktionstypen.", "Enable_strict_null_checks_6113": "Strenge NULL-Überprüfungen aktivieren.", "Enable_tracing_of_the_name_resolution_process_6085": "Ablaufverfolgung des Namensauflösungsvorgangs aktivieren.", "Enables_experimental_support_for_ES7_async_functions_6068": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Funktionen.", @@ -333,8 +335,12 @@ "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "Der Ausdruck wird in die Variablendeklaration \"{0}\" aufgelöst, die der Compiler verwendet, um asynchrone Funktionen zu unterstützen.", "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "Der Ausdruck wird in die Variablendeklaration \"_newTarget\" aufgelöst, die der Compiler zum Erfassen der Metaeigenschaftenreferenz \"new.target\" verwendet.", "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "Der Ausdruck wird in die Variablendeklaration \"_this\" aufgelöst, die der Compiler verwendet, um den this-Verweis zu erfassen.", - "Extract_function_95003": "Funktion extrahieren", - "Extract_to_0_95004": "Extrahieren in {0}", + "Extract_constant_95006": "Konstante extrahieren", + "Extract_function_95005": "Funktion extrahieren", + "Extract_symbol_95003": "Symbol extrahieren", + "Extract_to_0_in_1_95004": "Nach {0} in {1} extrahieren", + "Extract_to_0_in_1_scope_95008": "Nach {0} in {1}-Bereich extrahieren", + "Extract_to_0_in_enclosing_scope_95007": "Nach {0} in einschließenden Bereich extrahieren", "FILE_6035": "DATEI", "FILE_OR_DIRECTORY_6040": "DATEI ODER VERZEICHNIS", "Failed_to_parse_file_0_Colon_1_5014": "Fehler beim Analysieren der Datei \"{0}\": {1}.", @@ -424,6 +430,10 @@ "Invalid_use_of_0_in_strict_mode_1100": "Ungültige Verwendung von \"{0}\" im Strict-Modus.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Ungültiger Wert für \"jsxFactory\". \"{0}\" ist kein gültiger Bezeichner oder qualifizierter Name.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Ungültiger Wert für \"-reactNamespace\". \"{0}\" ist kein gültiger Bezeichner.", + "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "\"@augments {0}\" in JSDoc entspricht nicht der Klausel \"extends {1}\".", + "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "\"@augments\" in JSDoc ist keiner Klassendeklaration zugeordnet.", + "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Das JSDoc-Tag \"@param\" weist den Namen \"{0}\" auf, es gibt jedoch keinen Parameter dieses Namens.", + "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Das JSDoc-Tag \"@typedef\" muss entweder eine Typanmerkung aufweisen, oder die Tags \"@property\" oder \"@member\" müssen darauf folgen.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc-Typen können nur innerhalb von Dokumentationskommentaren verwendet werden.", "JSX_attribute_expected_17003": "Ein JSX-Attribut wurde erwartet.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX-Attributen darf nur ein nicht leeres expression-Objekt zugewiesen werden.", @@ -468,7 +478,6 @@ "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "Das Modul \"{0}\" verwendet \"export =\" und darf nicht mit \"export *\" verwendet werden.", "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "Das Modul \"{0}\" wurde als in \"{1}\" deklariertes Umgebungsmodul aufgelöst, weil diese Datei nicht geändert wurde.", "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "Das Modul \"{0}\" wurde als lokal deklariertes Umgebungsmodul in der Datei \"{1}\" aufgelöst.", - "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143": "Das Modul \"{0}\" wurde zu \"{1}\" aufgelöst, aber \"--allowJs\" wurde nicht festgelegt.", "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "Das Modul \"{0}\" wurde zu \"{1}\" aufgelöst, aber \"--jsx\" wurde nicht festgelegt.", "Module_Resolution_Options_6174": "Modulauflösungsoptionen", "Module_name_0_matched_pattern_1_6092": "Modulname \"{0}\", übereinstimmendes Muster \"{1}\".", @@ -656,7 +665,7 @@ "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript-Zielversion angeben: ES3 (Standard), ES5, ES2015, ES2016, ES2017 oder ESNEXT.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX-Codegenerierung angeben: \"preserve\", \"react-native\" oder \"react\".", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Geben Sie Bibliotheksdateien an, die in die Kompilierung eingeschlossen werden sollen: ", - "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Codeerstellung für das Modul angeben: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\" \"es2015\" oder \"ESNext\".", + "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Geben Sie die Codegenerierung für das Modul an: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\" oder \"ESNext\".", "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069": "Geben Sie die Modulauflösungsstrategie an: \"node\" (Node.js) oder \"classic\" (TypeScript vor Version 1.6).", "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146": "Geben Sie die JSX-Factoryfunktion an, die für eine react-JSX-Ausgabe verwendet werden soll, z. B. \"React.createElement\" oder \"h\".", "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "Geben Sie die Zeilenendesequenz an, die beim Ausgeben von Dateien verwendet werden soll: \"CRLF\" (DOS) oder \"LF\" (Unix).", @@ -691,10 +700,9 @@ "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "Auf das Objekt \"arguments\" darf in einer asynchronen Funktion oder Methode in ES3 und ES5 nicht verwiesen werden. Verwenden Sie ggf. eine Standardfunktion oder -methode.", "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "Der Text einer \"if\"-Anweisung kann keine leere Anweisung sein.", "The_character_set_of_the_input_files_6163": "Der Zeichensatz der Eingabedateien.", - "The_config_file_0_found_doesn_t_contain_any_source_files_6129": "Die gefundene Konfigurationsdatei \"{0}\" enthält keine Quelldateien.", "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Der beinhaltende Funktions- oder Modulkörper ist zu groß für eine Ablaufsteuerungsanalyse.", "The_current_host_does_not_support_the_0_option_5001": "Der aktuelle Host unterstützt die Option \"{0}\" nicht.", - "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "The expression of an export assignment must be an identifier or qualified name in an ambient context.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Der Ausdruck einer Exportzuweisung muss ein Bezeichner oder ein qualifizierter Name in einem Umgebungskontext sein.", "The_files_list_in_config_file_0_is_empty_18002": "Die Liste \"files\" in der Konfigurationsdatei \"{0}\" ist leer.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Der erste Parameter der \"then\"-Methode einer Zusage muss ein Rückruf sein.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Der globale Typ \"JSX.{0}\" darf nur eine Eigenschaft aufweisen.", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 9d493e7492402..7400710ad891c 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -533,7 +533,7 @@ - + @@ -2399,7 +2399,7 @@ - + diff --git a/lib/esn/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json similarity index 99% rename from lib/esn/diagnosticMessages.generated.json rename to lib/es/diagnosticMessages.generated.json index dbf6bb1d5bdbb..c5b12700b3410 100644 --- a/lib/esn/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Una expresión \"yield\" solo se permite en un cuerpo de generador.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "No se puede acceder al método abstracto '{0}' de la clase '{1}' mediante una expresión super.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Los métodos abstractos solo pueden aparecer en una clase abstracta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "No se puede acceder a la propiedad abstracta \"{0}\" de la clase \"{1}\" en el constructor.", "Accessibility_modifier_already_seen_1028": "El modificador de accesibilidad ya se ha visto.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Los descriptores de acceso solo están disponibles cuando el destino es ECMAScript 5 y versiones posteriores.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Un miembro de objeto no se puede declarar como opcional.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Una signatura de sobrecarga no se puede declarar como generador.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "No se admite una expresión unaria con el operador '{0}' en el lado izquierdo de una expresión de exponenciación. Considere la posibilidad de incluir la expresión entre paréntesis.", + "Annotate_with_type_from_JSDoc_95009": "Anotar con tipo de JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Anotar con tipos de JSDoc", "Argument_expression_expected_1135": "Se esperaba una expresión de argumento.", "Argument_for_0_option_must_be_Colon_1_6046": "El argumento para la opción '{0}' debe ser: {1}.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "No se puede asignar un argumento de tipo '{0}' al parámetro de tipo '{1}'.", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "Se esperaba un dígito binario.", "Binding_element_0_implicitly_has_an_1_type_7031": "El elemento de enlace '{0}' tiene un tipo '{1}' implícito.", "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable con ámbito de bloque '{0}' usada antes de su declaración.", + "Call_decorator_expression_90028": "Llame a la expresión decorador.", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signatura de llamada, que carece de una anotación de tipo de valor devuelto, tiene implícitamente un tipo de valor devuelto \"any\".", "Call_target_does_not_contain_any_signatures_2346": "El destino de llamada no contiene signaturas.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "No se puede acceder a \"{0}.{1}\" porque \"{0}\" es un tipo, no un espacio de nombres. ¿Su intención era recuperar el tipo de la propiedad \"{1}\" en \"{0}\" con \"{0}[\"{1}\"]\"?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "No se puede escribir en el archivo '{0}' porque sobrescribiría el archivo de entrada.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "La variable de la cláusula catch no puede tener una anotación de tipo.", "Catch_clause_variable_cannot_have_an_initializer_1197": "La variable de la cláusula catch no puede tener un inicializador.", - "Change_0_to_1_90014": "Cambia {0} a {1}.", + "Change_0_to_1_90014": "Cambie \"{0}\" a \"{1}\".", "Change_extends_to_implements_90003": "Cambiar \"extends\" por \"implements\".", "Change_spelling_to_0_90022": "Cambiar la ortografía a \"{0}\".", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Comprobando si '{0}' es el prefijo coincidente más largo para '{1}' - '{2}'.", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "La clase '{0}' extiende la clase base '{1}' de forma incorrecta.", "Class_0_incorrectly_implements_interface_1_2420": "La clase '{0}' implementa la interfaz '{1}' de forma incorrecta.", "Class_0_used_before_its_declaration_2449": "Se ha usado la clase \"{0}\" antes de declararla.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Las declaraciones de clase no pueden tener más de una etiqueta \"@augments\" o \"@extends\".", "Class_name_cannot_be_0_2414": "El nombre de la clase no puede ser \"{0}\".", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "El lado estático de la clase '{0}' extiende el lado estático de la clase base '{1}' de forma incorrecta.", "Classes_can_only_extend_a_single_class_1174": "Las clases solo pueden extender una clase única.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "Falta la signatura de índice en el tipo '{0}'.", "Index_signatures_are_incompatible_2330": "Las signaturas de índice no son compatibles.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Las declaraciones individuales de la declaración '{0}' combinada deben ser todas exportadas o todas locales.", + "Infer_parameter_types_from_usage_95012": "Infiera los tipos de parámetro del uso.", + "Infer_type_of_0_from_usage_95011": "Infiera el tipo de \"{0}\" del uso.", "Initialize_property_0_in_the_constructor_90020": "Inicialice la propiedad \"{0}\" en el constructor.", "Initialize_static_property_0_90021": "Inicialice la propiedad estática \"{0}\".", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "El inicializador de la variable miembro de instancia '{0}' no puede hacer referencia al identificador '{1}' declarado en el constructor.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "Uso no válido de '{0}' en modo strict.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor no válido para \"jsxFactory\". \"{0}\" no es un nombre calificado o un identificador válido.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor no válido para '--reactNamespace'. '{0}' no es un identificador válido.", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "La etiqueta \"@augments {0}\" de JSDoc no coincide con la cláusula \"extends {1}\".", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "La etiqueta \"@augments\" de JSDoc no está asociada a una declaración de clase.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La etiqueta \"@{0} {1}\" de JSDoc no coincide con la cláusula \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "La etiqueta \"@{0}\" de JSDoc no está asociada a una clase.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La etiqueta \"@param\" de JSDoc tiene el nombre \"{0}\", pero no hay ningún parámetro con ese nombre.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La etiqueta \"@typedef\" de JSDoc debe tener una anotación de tipo o ir seguida de las etiquetas \"@property\" o \"@member\".", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Los tipos JSDoc solo se pueden usar en los comentarios de la documentación.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "El tipo de elementos iterados de un operando \"yield*\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "El tipo de operando \"yield\" en un generador asincrónico debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", "Type_parameter_0_has_a_circular_constraint_2313": "El parámetro de tipo '{0}' tiene una restricción circular.", + "Type_parameter_0_has_a_circular_default_2716": "El parámetro de tipo \"{0}\" tiene un valor circular predeterminado.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "El parámetro de tipo '{0}' de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{1}'.", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "El parámetro de tipo '{0}' de la signatura de constructor de la interfaz exportada tiene o usa el nombre privado '{1}'.", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "El parámetro de tipo '{0}' de la clase exportada tiene o usa el nombre privado '{1}'.", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "Inspeccionar archivos de entrada.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "No se puede cambiar el nombre de elementos definidos en la biblioteca TypeScript estándar.", "You_cannot_rename_this_element_8000": "No se puede cambiar el nombre a este elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" no acepta suficientes argumentos para utilizarse como decorador aquí. ¿Pretendía llamar primero y escribir \"@{0}()\"?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" se especifica dos veces. El atributo denominado \"{0}\" se sobrescribirá.", "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' solo se puede usar en un archivo .ts.", "_0_expected_1005": "Se esperaba '{0}'.", diff --git a/lib/fra/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json similarity index 98% rename from lib/fra/diagnosticMessages.generated.json rename to lib/fr/diagnosticMessages.generated.json index 437b261393a47..c9c669f511ef2 100644 --- a/lib/fra/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Une expression 'yield' est autorisée uniquement dans le corps d'un générateur.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "La méthode abstraite '{0}' de la classe '{1}' n'est pas accessible au moyen de l'expression super.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Les méthodes abstraites peuvent uniquement apparaître dans une classe abstraite.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "La propriété abstraite '{0}' de la classe '{1}' n'est pas accessible dans le constructeur.", "Accessibility_modifier_already_seen_1028": "Modificateur d'accessibilité déjà rencontré.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Les accesseurs sont uniquement disponibles quand EcmaScript 5 ou version supérieure est ciblé.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Impossible de déclarer un membre d'objet comme étant facultatif.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Une signature de surcharge ne peut pas être déclarée en tant que générateur.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Une expression unaire avec l'opérateur '{0}' n'est pas autorisée dans la partie gauche d'une expression d'élévation à une puissance. Mettez l'expression entre parenthèses.", + "Annotate_with_type_from_JSDoc_95009": "Annoter avec le type de JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Annoter avec les types de JSDoc", "Argument_expression_expected_1135": "Expression d'argument attendue.", "Argument_for_0_option_must_be_Colon_1_6046": "L'argument de l'option '{0}' doit être {1}.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argument de type '{0}' n'est pas attribuable au paramètre de type '{1}'.", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "Chiffre binaire attendu.", "Binding_element_0_implicitly_has_an_1_type_7031": "L'élément de liaison '{0}' possède implicitement un type '{1}'.", "Block_scoped_variable_0_used_before_its_declaration_2448": "Variable de portée de bloc '{0}' utilisée avant sa déclaration.", + "Call_decorator_expression_90028": "Appelez l'expression de l'élément décoratif.", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La signature d'appel, qui ne dispose pas d'annotation de type de retour, possède implicitement un type de retour 'any'.", "Call_target_does_not_contain_any_signatures_2346": "La cible de l'appel ne contient aucune signature.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Impossible d'accéder à '{0}.{1}', car '{0}' est un type, mais pas un espace de noms. Voulez-vous plutôt récupérer le type de la propriété '{1}' dans '{0}' avec '{0}[\"{1}\"]' ?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Impossible d'écrire le fichier '{0}', car cela entraînerait le remplacement du fichier d'entrée.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Une variable de clause catch ne peut pas avoir d'annotation de type.", "Catch_clause_variable_cannot_have_an_initializer_1197": "Une variable de clause catch ne peut pas avoir d'initialiseur.", - "Change_0_to_1_90014": "Changez {0} en {1}.", + "Change_0_to_1_90014": "Changez '{0}' en '{1}'.", "Change_extends_to_implements_90003": "Changez 'extends' en 'implements'.", "Change_spelling_to_0_90022": "Changez l'orthographe en '{0}'.", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Vérification en cours pour déterminer si '{0}' est le préfixe correspondant le plus long pour '{1}' - '{2}'.", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' étend de manière incorrecte la classe de base '{1}'.", "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implémente de manière incorrecte l'interface '{1}'.", "Class_0_used_before_its_declaration_2449": "Classe '{0}' utilisée avant sa déclaration.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Les déclarations de classes ne peuvent pas avoir plusieurs balises '@augments' ou '@extends'.", "Class_name_cannot_be_0_2414": "Le nom de la classe ne peut pas être '{0}'.", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Le côté statique de la classe '{0}' étend de manière incorrecte le côté statique de la classe de base '{1}'.", "Classes_can_only_extend_a_single_class_1174": "Les classes ne peuvent étendre qu'une seule classe.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "Signature d'index manquante dans le type '{0}'.", "Index_signatures_are_incompatible_2330": "Les signatures d'index sont incompatibles.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Les déclarations individuelles de la déclaration fusionnée '{0}' doivent toutes être exportées ou locales.", + "Infer_parameter_types_from_usage_95012": "Déduisez les types des paramètres à partir de l'utilisation.", + "Infer_type_of_0_from_usage_95011": "Déduisez le type de '{0}' à partir de l'utilisation.", "Initialize_property_0_in_the_constructor_90020": "Initialisez la propriété '{0}' dans le constructeur.", "Initialize_static_property_0_90021": "Initialisez la propriété statique '{0}'.", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'initialiseur de la variable membre d'instance '{0}' ne peut pas référencer l'identificateur '{1}' déclaré dans le constructeur.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "Utilisation non valide de '{0}' en mode strict.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valeur non valide pour 'jsxFactory'. '{0}' n'est pas un identificateur valide ou un nom qualifié.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valeur non valide pour '--reactNamespace'. '{0}' n'est pas un identificateur valide.", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "La balise JSDoc '@augments {0}' ne correspond pas à la clause 'extends {1}'.", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "La balise JSDoc '@augments' n'est pas attaché à une déclaration de classe.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La balise JSDoc '@{0} {1}' ne correspond pas à la clause 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "La balise JSDoc '@{0}' n'est pas attachée à une classe.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "La balise JSDoc '@param' se nomme '{0}', mais il n'existe aucun paramètre portant ce nom.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La balise JSDoc '@typedef' doit avoir une annotation de type ou être suivie des balises '@property' ou '@member'.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Les types JSDoc peuvent uniquement être utilisés dans les commentaires de la documentation.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Le type des éléments itérés d'un opérande 'yield*' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Le type d'un opérande 'yield' dans un générateur asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", "Type_parameter_0_has_a_circular_constraint_2313": "Le paramètre de type '{0}' possède une contrainte circulaire.", + "Type_parameter_0_has_a_circular_default_2716": "Le paramètre de type '{0}' a une valeur par défaut circulaire.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Le paramètre de type '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Le paramètre de type '{0}' de la signature de constructeur de l'interface exportée possède ou utilise le nom privé '{1}'.", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Le paramètre de type '{0}' de la classe exportée possède ou utilise le nom privé '{1}'.", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "Fichiers d'entrée d'espion.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Vous ne pouvez pas renommer des éléments définis dans la bibliothèque TypeScript standard.", "You_cannot_rename_this_element_8000": "Vous ne pouvez pas renommer cet élément.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accepte trop peu d'arguments pour pouvoir être utilisé ici en tant qu'élément décoratif. Voulez-vous vraiment l'appeler d'abord et écrire '@{0}()' ?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' spécifié deux fois. L'attribut nommé '{0}' va être remplacé.", "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' peut uniquement être utilisé dans un fichier .ts.", "_0_expected_1005": "'{0}' attendu.", diff --git a/lib/ita/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json similarity index 99% rename from lib/ita/diagnosticMessages.generated.json rename to lib/it/diagnosticMessages.generated.json index f3a0f9c0a0d14..06ee0af0a2c2e 100644 --- a/lib/ita/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Un'espressione 'yield' è consentita solo nel corpo di un generatore.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Non è possibile accedere al metodo astratto '{0}' nella classe '{1}' tramite l'espressione super.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "I metodi astratti possono essere inclusi solo in una classe astratta.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Non è possibile accedere alla proprietà astratta '{0}' nella classe '{1}' nel costruttore.", "Accessibility_modifier_already_seen_1028": "Il modificatore di accessibilità è già presente.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Le funzioni di accesso sono disponibili solo se destinate a ECMAScript 5 e versioni successive.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Un membro di oggetto non può essere dichiarato come facoltativo.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Non è possibile dichiarare come generatore una firma di overload.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Nella parte sinistra di un'espressione di elevamento a potenza non è consentita un'espressione unaria con l'operatore '{0}'. Provare a racchiudere l'espressione tra parentesi.", + "Annotate_with_type_from_JSDoc_95009": "Annota con tipo di JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Annota con tipi di JSDoc", "Argument_expression_expected_1135": "È prevista l'espressione di argomento.", "Argument_for_0_option_must_be_Colon_1_6046": "L'argomento per l'opzione '{0}' deve essere {1}.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "L'argomento di tipo '{0}' non è assegnabile al parametro di tipo '{1}'.", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "È prevista una cifra binaria.", "Binding_element_0_implicitly_has_an_1_type_7031": "L'elemento di binding '{0}' contiene implicitamente un tipo '{1}'.", "Block_scoped_variable_0_used_before_its_declaration_2448": "La variabile con ambito blocco '{0}' è stata usata prima di essere stata dichiarata.", + "Call_decorator_expression_90028": "Chiama l'espressione Decorator.", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "La firma di chiamata, in cui manca l'annotazione di tipo restituito, contiene implicitamente un tipo restituito 'any'.", "Call_target_does_not_contain_any_signatures_2346": "La destinazione della chiamata non contiene alcuna firma.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Non è possibile accedere a '{0}.{1}' perché '{0}' è un tipo ma non uno spazio dei nomi. Si intendeva recuperare il tipo della proprietà '{1}' in '{0}' con '{0}[\"{1}\"]'?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Non è possibile scrivere il file '{0}' perché sovrascriverebbe il file di input.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "La variabile della clausola catch non può contenere un'annotazione di tipo.", "Catch_clause_variable_cannot_have_an_initializer_1197": "La variabile della clausola catch non può contenere un inizializzatore.", - "Change_0_to_1_90014": "Cambia {0} in {1}.", + "Change_0_to_1_90014": "Cambia '{0}' in '{1}'.", "Change_extends_to_implements_90003": "Cambia 'extends' in 'implements'.", "Change_spelling_to_0_90022": "Modificare l'ortografia in '{0}'.", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Verrà verificato se '{0}' è il prefisso di corrispondenza più lungo per '{1}' - '{2}'.", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' estende in modo errato la classe di base '{1}'.", "Class_0_incorrectly_implements_interface_1_2420": "La classe '{0}' implementa in modo errato l'interfaccia '{1}'.", "Class_0_used_before_its_declaration_2449": "La classe '{0}' è stata usata prima di essere stata dichiarata.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Le dichiarazioni di classe non possono contenere più di un tag `@augments` o `@extends`.", "Class_name_cannot_be_0_2414": "Il nome della classe non può essere '{0}'.", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Il lato statico '{0}' della classe estende in modo errato il lato statico '{1}' della classe di base.", "Classes_can_only_extend_a_single_class_1174": "Le classi possono estendere solo un'unica classe.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "Nel tipo '{0}' manca la firma dell'indice.", "Index_signatures_are_incompatible_2330": "Le firme dell'indice sono incompatibili.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Le singole dichiarazioni della dichiarazione sottoposta a merge '{0}' devono essere tutte esportate o tutte locali.", + "Infer_parameter_types_from_usage_95012": "Deriva i tipi di parametro dall'utilizzo.", + "Infer_type_of_0_from_usage_95011": "Deriva il tipo di '{0}' dall'utilizzo.", "Initialize_property_0_in_the_constructor_90020": "Inizializza la proprietà '{0}' nel costruttore.", "Initialize_static_property_0_90021": "Inizializza la proprietà statica '{0}'.", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'inizializzatore della variabile del membro di istanza '{0}' non può fare riferimento all'identificatore '{1}' dichiarato nel costruttore.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "Uso non valido di '{0}' in modalità strict.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Il valore non è valido per 'jsxFactory'. '{0}' non è un identificatore o un nome qualificato valido.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Il valore di '--reactNamespace' non è valido. '{0}' non è un identificatore valido", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "Il tag '@augments {0}' di JSDoc non corrisponde alla clausola 'extends {1}'.", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "Il tag '@augments' di JSDoc non è collegato a una dichiarazione di classe.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Il tag '@{0} {1}' di JSDoc non corrisponde alla clausola 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Il tag '@{0}' di JSDoc non è collegato a una classe.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Il nome del tag '@param' di JSDoc è '{0}', ma non esiste alcun parametro con questo nome.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Il tag '@typedef' di JSDoc deve contenere un'annotazione di tipo o essere seguito dal tag '@property' o '@member'.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "I tipi JSDoc possono essere usati solo nei commenti della documentazione.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Il tipo di elementi iterati di un operando 'yield*' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Il tipo dell'operando 'yield' in un generatore asincrono deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", "Type_parameter_0_has_a_circular_constraint_2313": "Il parametro di tipo '{0}' contiene un vincolo circolare.", + "Type_parameter_0_has_a_circular_default_2716": "Il parametro di tipo '{0}' contiene un'impostazione predefinita circolare.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Il parametro di tipo '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Il parametro di tipo '{0}' della firma del costruttore dell'interfaccia esportata contiene o usa il nome privato '{1}'.", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Il parametro di tipo '{0}' della classe esportata contiene o usa il nome privato '{1}'.", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "Controlla i file di input.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Non è possibile rinominare elementi definiti nella libreria TypeScript standard.", "You_cannot_rename_this_element_8000": "Non è possibile rinominare questo elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accetta un numero troppo ridotto di argomenti da usare come espressione Decorator in questo punto. Si intendeva chiamarlo prima e scrivere '@{0}()'?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Gli attributi '{0}' sono stati specificati due volte. L'attributo denominato '{0}' verrà sovrascritto.", "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' può essere usato solo in un file con estensione ts.", "_0_expected_1005": "È previsto '{0}'.", diff --git a/lib/jpn/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json similarity index 99% rename from lib/jpn/diagnosticMessages.generated.json rename to lib/ja/diagnosticMessages.generated.json index b6f3e2e65596b..dc947a812a28f 100644 --- a/lib/jpn/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 式は、ジェネレーター本文でのみ使用できます。", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "クラス '{1}' の抽象メソッド '{0}' には super 式を介してアクセスできません。", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象メソッドは抽象クラス内でのみ使用できます。", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "コンストラクター内でクラス '{1}' の抽象プロパティ '{0}' にアクセスできません。", "Accessibility_modifier_already_seen_1028": "アクセシビリティ修飾子は既に存在します。", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "アクセサーは ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", "Accessors_must_both_be_abstract_or_non_abstract_2676": "アクセサーはどちらも抽象または非抽象である必要があります。", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "オブジェクト メンバーを省略可能として宣言することはできません。", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "オーバーロード シグネチャをジェネレーターとして宣言することはできません。", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "累乗式の左辺で '{0}' 演算子を含む単項式を使用することはできません。式を括弧で囲むことを検討してください。", + "Annotate_with_type_from_JSDoc_95009": "JSDoc の型で注釈を付けます", + "Annotate_with_types_from_JSDoc_95010": "JSDoc の型で注釈を付けます", "Argument_expression_expected_1135": "引数式が必要です。", "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' オプションの引数は {1} である必要があります。", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "型 '{0}' の引数を型 '{1}' のパラメーターに割り当てることはできません。", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "2 進の数字が必要です。", "Binding_element_0_implicitly_has_an_1_type_7031": "バインド要素 '{0}' には暗黙的に '{1}' 型が含まれます。", "Block_scoped_variable_0_used_before_its_declaration_2448": "ブロック スコープの変数 '{0}' が、宣言の前に使用されています。", + "Call_decorator_expression_90028": "デコレーター式を呼び出します。", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "戻り値の型の注釈がない呼び出しシグネチャの戻り値の型は、暗黙的に 'any' になります。", "Call_target_does_not_contain_any_signatures_2346": "呼び出しターゲットにシグネチャが含まれていません。", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}.{1}' にアクセスできません。'{0}' は型で、名前空間ではありません。'{0}[\"{1}\"]' で '{0}' のプロパティ '{1}' の型を取得するつもりでしたか?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "入力ファイルを上書きすることになるため、ファイル '{0}' を書き込めません。", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "catch 句の変数に型の注釈を指定することはできません。", "Catch_clause_variable_cannot_have_an_initializer_1197": "catch 句の変数に初期化子を指定することはできません。", - "Change_0_to_1_90014": "{0} を {1} に変更します。", + "Change_0_to_1_90014": "'{0}' を '{1}' に変更します。", "Change_extends_to_implements_90003": "'extends' を 'implements' に変更します。", "Change_spelling_to_0_90022": "スペルを '{0}' に変更してください。", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}' が '{1}' - '{2}' の最長一致のプレフィックスであるかを確認しています。", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "クラス '{0}' は基底クラス '{1}' を正しく拡張していません。", "Class_0_incorrectly_implements_interface_1_2420": "クラス '{0}' はインターフェイス '{1}' を正しく実装していません。", "Class_0_used_before_its_declaration_2449": "クラス '{0}' は宣言の前に使用されました。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "クラス宣言で複数の '@augments' または `@extends` タグを使用することはできません。", "Class_name_cannot_be_0_2414": "クラス名を '{0}' にすることはできません。", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "クラス側の静的な '{0}' が基底クラス側の静的な '{1}' を正しく拡張していません。", "Classes_can_only_extend_a_single_class_1174": "クラスで拡張できるクラスは 1 つのみです。", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "型 '{0}' のインデックス シグネチャがありません。", "Index_signatures_are_incompatible_2330": "インデックスの署名に互換性がありません。", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "マージされた宣言 '{0}' の個々の宣言はすべてエクスポートされるか、すべてローカルであるかのどちらかである必要があります。", + "Infer_parameter_types_from_usage_95012": "使用状況からパラメーターの型を推論します。", + "Infer_type_of_0_from_usage_95011": "使用状況から型 '{0}' を推論します。", "Initialize_property_0_in_the_constructor_90020": "コンストラクターのプロパティ '{0}' を初期化します。", "Initialize_static_property_0_90021": "静的プロパティ '{0}' を初期化します。", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "インスタンス メンバー変数 '{0}' の初期化子はコンストラクターで宣言された識別子 '{1}' を参照できません。", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "厳格モードでは '{0}' の使用は無効です。", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' の値が無効です。'{0}' が有効な識別子または修飾名ではありません。", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' の値が無効です。'{0}' は有効な識別子ではありません。", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "JSDoc '@augments {0}' は 'extends {1}' 句と一致しません。", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "JSDoc '@augments' はクラス宣言にアタッチされていません。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' が 'extends {2}' 句と一致しません。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' はクラスにアタッチされていません。", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' タグの名前は '{0}' ですが、その名前のパラメーターはありません。", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' タグには、型の注釈を指定するか、後に '@property' タグや '@member' タグを付ける必要があります。", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc の種類は、ドキュメント コメント内でのみ使用できます。", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' オペランドの反復要素の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同期ジェネレーター内の 'yield' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", "Type_parameter_0_has_a_circular_constraint_2313": "型パラメーター '{0}' に循環制約があります。", + "Type_parameter_0_has_a_circular_default_2716": "型パラメーター '{0}' に循環既定値があります。", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "エクスポートされたインターフェイスの呼び出しシグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "エクスポートされたインターフェイスのコンストラクター シグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "エクスポートされたクラスの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "入力ファイルを監視します。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "標準の TypeScript ライブラリで定義された要素の名前を変更することはできません。", "You_cannot_rename_this_element_8000": "この要素の名前を変更することはできません。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' は受け入れる引数が少なすぎるので、ここでデコレーターとして使用することができません。最初にこれを呼び出してから、'@{0}()' を書き込むつもりでしたか?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' は 2 回指定されています。'{0}' という名前の属性は上書きされます。", "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' を使用できるのは .ts ファイル内のみです。", "_0_expected_1005": "'{0}' が必要です。", diff --git a/lib/kor/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json similarity index 98% rename from lib/kor/diagnosticMessages.generated.json rename to lib/ko/diagnosticMessages.generated.json index d1837c5a7fa3b..0e73de4b98603 100644 --- a/lib/kor/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "'yield' 식은 생성기 본문에서만 사용할 수 있습니다.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "super 식을 통해 '{1}' 클래스의 추상 메서드 '{0}'에 액세스할 수 없습니다.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "추상 메서드는 추상 클래스 내에서만 사용할 수 있습니다.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "생성자에서 '{1}' 클래스의 추상 속성 '{0}'에 액세스할 수 없습니다.", "Accessibility_modifier_already_seen_1028": "액세스 가능성 한정자가 이미 있습니다.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "접근자는 ECMAScript 5 이상을 대상으로 지정할 때만 사용할 수 있습니다.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "접근자는 모두 추상이거나 비추상이어야 합니다.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "개체 멤버는 선택적으로 선언될 수 없습니다.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "오버로드 시그니처는 생성기로 선언할 수 없습니다.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "지수 식의 왼쪽에는 '{0}' 연산자가 있는 단항 식을 사용할 수 없습니다. 식을 괄호로 묶는 것이 좋습니다.", + "Annotate_with_type_from_JSDoc_95009": "JSDoc의 형식을 사용하여 주석 추가", + "Annotate_with_types_from_JSDoc_95010": "JSDoc의 형식을 사용하여 주석 추가", "Argument_expression_expected_1135": "인수 식이 필요합니다.", "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' 옵션의 인수는 {1}이어야(여야) 합니다.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "'{0}' 형식의 인수는 '{1}' 형식의 매개 변수에 할당될 수 없습니다.", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "이진수가 있어야 합니다.", "Binding_element_0_implicitly_has_an_1_type_7031": "바인딩 요소 '{0}'에 암시적으로 '{1}' 형식이 있습니다.", "Block_scoped_variable_0_used_before_its_declaration_2448": "선언 전에 사용된 블록 범위 변수 '{0}'입니다.", + "Call_decorator_expression_90028": "decorator 식을 호출합니다.", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "반환 형식 주석이 없는 호출 시그니처에는 암시적으로 'any' 반환 형식이 포함됩니다.", "Call_target_does_not_contain_any_signatures_2346": "호출 대상에 시그니처가 포함되어 있지 않습니다.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "'{0}'이(가) 네임스페이스가 아니라 형식이므로 '{0}.{1}'에 액세스할 수 없습니다. '{0}'에서 '{0}[\"{1}\"]'과(와) 함께 '{1}' 속성의 형식을 검색하려고 했나요?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "'{0}' 파일은 입력 파일을 덮어쓰므로 쓸 수 없습니다.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 절 변수에 형식 주석을 사용할 수 없습니다.", "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 절 변수에 이니셜라이저를 사용할 수 없습니다.", - "Change_0_to_1_90014": "{0}을(를) {1}(으)로 변경합니다.", + "Change_0_to_1_90014": "'{0}'을(를) '{1}'(으)로 변경합니다.", "Change_extends_to_implements_90003": "'extends'를 'implements'로 변경하세요.", "Change_spelling_to_0_90022": "철자를 '{0}'(으)로 변경하세요.", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}'이(가) '{1}' - '{2}'에 대해 일치하는 가장 긴 접두사인지 확인하는 중입니다.", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' 클래스가 기본 클래스 '{1}'을(를) 잘못 확장합니다.", "Class_0_incorrectly_implements_interface_1_2420": "'{0}' 클래스가 '{1}' 인터페이스를 잘못 구현합니다.", "Class_0_used_before_its_declaration_2449": "선언 전에 사용된 '{0}' 클래스입니다.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "클래스 선언은 '@augments' 또는 `@extends` 태그를 둘 이상 가질 수 없습니다.", "Class_name_cannot_be_0_2414": "클래스 이름은 '{0}'일 수 없습니다.", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "클래스 정적 측면 '{0}'이(가) 기본 클래스 정적 측면 '{1}'을(를) 잘못 확장합니다.", "Classes_can_only_extend_a_single_class_1174": "클래스는 단일 클래스만 확장할 수 있습니다.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "'{0}' 형식에 인덱스 시그니처가 없습니다.", "Index_signatures_are_incompatible_2330": "인덱스 시그니처가 호환되지 않습니다.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "병합된 선언 '{0}'의 개별 선언은 모두 내보내 졌거나 모두 로컬이어야 합니다.", + "Infer_parameter_types_from_usage_95012": "사용량에서 매개 변수 형식을 유추합니다.", + "Infer_type_of_0_from_usage_95011": "사용량에서 '{0}'의 형식을 유추합니다.", "Initialize_property_0_in_the_constructor_90020": "생성자에서 속성 '{0}'을(를) 초기화합니다.", "Initialize_static_property_0_90021": "정적 속성 '{0}'을(를) 초기화합니다.", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "인스턴스 멤버 변수 '{0}'의 이니셜라이저는 생성자에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "strict 모드에서 '{0}'을(를) 잘못 사용했습니다.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory'에 대한 값이 잘못되었습니다. '{0}'이(가) 올바른 식별자 또는 정규화된 이름이 아닙니다.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace'의 값이 잘못되었습니다. '{0}'은(는) 올바른 식별자가 아닙니다.", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "JSDoc '@augments {0}'이(가) 'extends {1}' 절과 일치하지 않습니다.", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "JSDoc '@augments'가 클래스 선언에 연결되어 있지 않습니다.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}'이(가) 'extends {2}' 절과 일치하지 않습니다.", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}'이(가) 클래스에 연결되어 있지 않습니다.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' 태그의 이름이 '{0}'인데 해당 이름의 매개 변수가 없습니다.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 태그는 형식 주석을 포함하거나, '@property' 또는 '@member' 태그 앞에 와야 합니다.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 유형은 문서 주석 내에서만 사용될 수 있습니다.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*'의 반복되는 요소 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_parameter_0_has_a_circular_constraint_2313": "형식 매개 변수 '{0}'에 순환 제약 조건이 있습니다.", + "Type_parameter_0_has_a_circular_default_2716": "형식 매개 변수 '{0}'에 순환 기본값이 있습니다.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "내보낸 인터페이스에 있는 호출 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "내보낸 인터페이스에 있는 생성자 시그니처의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "내보낸 클래스의 형식 매개 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "조사식 입력 파일입니다.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "표준 TypeScript 라이브러리에 정의된 요소의 이름을 바꿀 수 없습니다.", "You_cannot_rename_this_element_8000": "이 요소의 이름을 바꿀 수 없습니다.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}'이(가) 여기에서 decorator로 사용할 인수를 너무 적게 허용합니다. 먼저 이를 호출하고 '@{0}()'을(를) 작성하시겠습니까?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}'이(가) 두 번 지정되었습니다. 이름이 '{0}'인 특성을 덮어씁니다.", "_0_can_only_be_used_in_a_ts_file_8009": "'{0}'은(는) .ts 파일에서만 사용할 수 있습니다.", "_0_expected_1005": "'{0}'이(가) 필요합니다.", diff --git a/lib/plk/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json similarity index 98% rename from lib/plk/diagnosticMessages.generated.json rename to lib/pl/diagnosticMessages.generated.json index eea1271578f83..49e73f00b2474 100644 --- a/lib/plk/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Wyrażenie „yield” jest dozwolone tylko w treści generatora.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Nie można uzyskać dostępu do metody abstrakcyjnej „{0}” w klasie „{1}” za pomocą wyrażenia super.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Metody abstrakcyjne mogą występować tylko w klasie abstrakcyjnej.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Właściwość abstrakcyjna „{0}” w klasie „{1}” jest niedostępna w konstruktorze.", "Accessibility_modifier_already_seen_1028": "Napotkano już modyfikator dostępności.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Metody dostępu są dostępne tylko wtedy, gdy jest używany język ECMAScript 5 lub nowszy.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Obie metody dostępu muszą być abstrakcyjne lub nieabstrakcyjne.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Element członkowski obiektu nie może być zadeklarowany jako opcjonalny.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Sygnatura przeciążenia nie może być zadeklarowana jako generator.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Wyrażenie jednoargumentowe z operatorem „{0}” jest niedozwolone po lewej stronie wyrażenia potęgowania. Zastanów się nad zamknięciem wyrażenia w nawiasach.", + "Annotate_with_type_from_JSDoc_95009": "Dodaj adnotację przy użyciu typu z JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Dodaj adnotację przy użyciu typów z JSDoc", "Argument_expression_expected_1135": "Oczekiwano wyrażenia argumentu.", "Argument_for_0_option_must_be_Colon_1_6046": "Argumentem opcji „{0}” musi być: {1}.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Nie można przypisać argumentu typu „{0}” do parametru typu „{1}”.", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "Oczekiwano bitu.", "Binding_element_0_implicitly_has_an_1_type_7031": "Dla elementu powiązania „{0}” niejawnie określono typ „{1}”.", "Block_scoped_variable_0_used_before_its_declaration_2448": "Zmienna „{0}” o zakresie bloku została użyta przed jej deklaracją.", + "Call_decorator_expression_90028": "Wywołaj wyrażenie dekoratora.", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Dla sygnatury wywołania bez adnotacji zwracanego typu niejawnie określono zwracany typ „any”.", "Call_target_does_not_contain_any_signatures_2346": "Cel wywołania nie zawiera żadnych podpisów.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Nie można uzyskać dostępu do elementu „{0}.{1}”, ponieważ element „{0}” jest typem, ale nie przestrzenią nazw. Czy chcesz pobrać typ właściwości „{1}” w lokalizacji „{0}” za pomocą elementu „{0}[„{1}”]”?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Nie można zapisać pliku „{0}”, ponieważ nadpisałby plik wejściowy.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Zmienna klauzuli catch nie może mieć adnotacji typu.", "Catch_clause_variable_cannot_have_an_initializer_1197": "Zmienna klauzuli catch nie może mieć inicjatora.", - "Change_0_to_1_90014": "Zmień {0} na {1}.", + "Change_0_to_1_90014": "Zmień element „{0}” na „{1}”.", "Change_extends_to_implements_90003": "Zmień atrybut „extends” na „implements”.", "Change_spelling_to_0_90022": "Zmiana pisowni na „{0}”.", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Sprawdzanie, czy „{0}” to najdłuższy zgodny prefiks dla „{1}” — „{2}”.", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "Klasa „{0}” niepoprawnie rozszerza klasę podstawową „{1}”.", "Class_0_incorrectly_implements_interface_1_2420": "Klasa „{0}” zawiera niepoprawną implementację interfejsu „{1}”.", "Class_0_used_before_its_declaration_2449": "Klasa „{0}” została użyta przed zadeklarowaniem.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklaracje klas nie mogą mieć więcej niż jeden tag „@augments” lub „@extends”.", "Class_name_cannot_be_0_2414": "Klasa nie może mieć nazwy „{0}”.", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Strona statyczna klasy „{0}” niepoprawnie rozszerza stronę statyczną klasy podstawowej „{1}”.", "Classes_can_only_extend_a_single_class_1174": "Klasy mogą rozszerzać tylko pojedynczą klasę.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "Brak sygnatury indeksu w typie „{0}”.", "Index_signatures_are_incompatible_2330": "Sygnatury indeksów są niezgodne.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Wszystkie poszczególne deklaracje w scalonej deklaracji „{0}” muszą być wyeksportowane lub lokalne.", + "Infer_parameter_types_from_usage_95012": "Wywnioskuj typy parametrów na podstawie użycia.", + "Infer_type_of_0_from_usage_95011": "Wywnioskuj typ elementu „{0}” na podstawie użycia.", "Initialize_property_0_in_the_constructor_90020": "Zainicjuj właściwość „{0}” w konstruktorze.", "Initialize_static_property_0_90021": "Zainicjuj właściwość statyczną „{0}”.", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicjator zmiennej elementu członkowskiego wystąpienia „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego w konstruktorze.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "Nieprawidłowe użycie elementu „{0}” w trybie z ograniczeniami.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Nieprawidłowa wartość elementu „jsxFactory”. „{0}” to nie jest prawidłowy identyfikator ani kwalifikowana nazwa.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Nieprawidłowa wartość opcji „--reactNamespace”. Element „{0}” nie jest prawidłowym identyfikatorem.", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "Element JSDoc „@augments {0}” jest niezgodny z klauzulą „extends {1}”.", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "Element JSDoc „@augments” nie został dołączony do deklaracji klasy.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Element JSDoc „@{0} {1}” nie pasuje do klauzuli „extends {2}”.", + "JSDoc_0_is_not_attached_to_a_class_8022": "Element JSDoc „@{0}” nie został dołączony do klasy.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Tag JSDoc „@param” tag ma nazwę „{0}”, ale nie ma parametru o tej nazwie.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Tag JSDoc „@typedef” powinien mieć adnotację typu albo powinien następować po nim tag „@property” lub „@member”.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc mogą być używane wyłącznie w komentarzach dokumentacji.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterowanych elementów operandu „yield*” musi być prawidłową obietnicą lub nie może zawierać wywoływalnego elementu członkowskiego „then”.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu „yield” w generatorze asynchronicznym musi być prawidłową obietnicą lub nie może zawierać wywoływalnego elementu członkowskiego „then”.", "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu „{0}” zawiera ograniczenie cykliczne.", + "Type_parameter_0_has_a_circular_default_2716": "Parametr typu „{0}” ma cykliczną wartość domyślną.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu „{0}” sygnatury wywołania z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Parametr typu „{0}” sygnatury konstruktora z wyeksportowanego interfejsu ma nazwę prywatną „{1}” lub używa tej nazwy.", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Parametr typu „{0}” wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "Obserwuj pliki wejściowe.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nie można zmienić nazw elementów zdefiniowanych w standardowej bibliotece TypeScript.", "You_cannot_rename_this_element_8000": "Nie można zmienić nazwy tego elementu.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Element „{0}” akceptuje za mało argumentów, aby można go było użyć w tym miejscu jako dekorator. Czy chcesz najpierw go wywołać i zapisać tag „@{0}()”?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Element „{0}” został określony dwa razy. Atrybut o nazwie „{0}” zostanie przesłonięty.", "_0_can_only_be_used_in_a_ts_file_8009": "Elementu „{0}” można użyć tylko w pliku .ts.", "_0_expected_1005": "Oczekiwano elementu „{0}”.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 7304ec358d64a..6f28bb8a2d541 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -47,6 +47,7 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", @@ -68,6 +69,7 @@ declare namespace ts.server.protocol { * Client-initiated request message */ interface Request extends Message { + type: "request"; /** * The command to execute */ @@ -87,6 +89,7 @@ declare namespace ts.server.protocol { * Server-initiated event message */ interface Event extends Message { + type: "event"; /** * Name of event */ @@ -100,6 +103,7 @@ declare namespace ts.server.protocol { * Response by server to client request message. */ interface Response extends Message { + type: "response"; /** * Sequence number of the request message. */ @@ -113,7 +117,8 @@ declare namespace ts.server.protocol { */ command: string; /** - * Contains error message if success === false. + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. */ message?: string; /** @@ -389,6 +394,12 @@ declare namespace ts.server.protocol { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } interface FileRangeRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). @@ -416,6 +427,9 @@ declare namespace ts.server.protocol { */ errorCodes?: number[]; } + interface ApplyCodeActionCommandRequestArgs extends FileRequestArgs { + command: {}; + } /** * Response for GetCodeFixes request. */ @@ -1154,6 +1168,8 @@ declare namespace ts.server.protocol { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; } /** * Format and format on key response message. @@ -1260,6 +1276,11 @@ declare namespace ts.server.protocol { * this span should be used instead of the default one. */ replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; } /** * Additional completion entry details, available on demand @@ -1289,6 +1310,10 @@ declare namespace ts.server.protocol { * JSDoc tags for the symbol. */ tags: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; } interface CompletionsResponse extends Response { body?: CompletionEntry[]; @@ -2113,6 +2138,7 @@ declare namespace ts.server.protocol { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface JSDocTagInfo { diff --git a/lib/ptb/diagnosticMessages.generated.json b/lib/pt-BR/diagnosticMessages.generated.json similarity index 99% rename from lib/ptb/diagnosticMessages.generated.json rename to lib/pt-BR/diagnosticMessages.generated.json index 0336fa640b855..c138f9311c0b2 100644 --- a/lib/ptb/diagnosticMessages.generated.json +++ b/lib/pt-BR/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "A expressão 'yield' só é permitida em um corpo gerador.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "O método abstrato '{0}' na classe '{1}' não pode ser acessado por meio da expressão super.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Os métodos abstratos só podem aparecer dentro de uma classe abstrata.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "A propriedade abstrata '{0}' na classe '{1}' não pode ser acessada no construtor.", "Accessibility_modifier_already_seen_1028": "O modificador de acessibilidade já foi visto.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Os acessadores somente estão disponíveis no direcionamento para ECMAScript 5 e superior.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Acessadores devem ser abstratos ou não abstratos.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Um membro de objeto não pode ser declarado como opcional.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "A assinatura de sobrecarga não pode ser declarada como geradora.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Uma expressão unária com o operador '{0}' não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", + "Annotate_with_type_from_JSDoc_95009": "Anotar com o tipo do JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Anotar com os tipos do JSDoc", "Argument_expression_expected_1135": "Expressão de argumento esperada.", "Argument_for_0_option_must_be_Colon_1_6046": "O argumento para a opção '{0}' deve ser: {1}.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "O argumento do tipo '{0}' não é atribuível ao parâmetro do tipo '{1}'.", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "Dígito binário esperado.", "Binding_element_0_implicitly_has_an_1_type_7031": "O elemento de associação '{0}' tem implicitamente um tipo '{1}'.", "Block_scoped_variable_0_used_before_its_declaration_2448": "Variável de escopo de bloco '{0}' usada antes da sua declaração.", + "Call_decorator_expression_90028": "Chamar expressão decoradora.", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Assinatura de chamada, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno 'any'.", "Call_target_does_not_contain_any_signatures_2346": "O destino da chamada não contém nenhuma assinatura.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Não foi possível acessar '{0}.{1}' porque '{0}' é um tipo, mas não um namespace. Você quis dizer recuperar o tipo da propriedade '{1}' em '{0}' com '{0}[\"{1}\"]'?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Não é possível gravar o arquivo '{0}' porque ele substituiria o arquivo de entrada.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "A variável de cláusula catch não pode ter uma anotação de tipo.", "Catch_clause_variable_cannot_have_an_initializer_1197": "A variável de cláusula catch não pode ter um inicializador.", - "Change_0_to_1_90014": "Alterar {0} para {1}.", + "Change_0_to_1_90014": "Alterar '{0}' para '{1}'.", "Change_extends_to_implements_90003": "Altere 'extends' para 'implements'.", "Change_spelling_to_0_90022": "Alterar ortografia para '{0}'.", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Verificando se '{0}' é o maior prefixo correspondente para '{1}' - '{2}'.", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "A classe '{0}' estende incorretamente a classe base '{1}'.", "Class_0_incorrectly_implements_interface_1_2420": "A classe '{0}' implementa incorretamente a interface '{1}'.", "Class_0_used_before_its_declaration_2449": "Classe '{0}' usada antes de sua declaração.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Declarações de classe não podem ter mais de uma marca `@augments` ou `@extends`.", "Class_name_cannot_be_0_2414": "O nome de classe não pode ser '{0}'.", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "O lado estático da classe '{0}' incorretamente estende o lado estático da classe base '{1}'.", "Classes_can_only_extend_a_single_class_1174": "Classes só podem estender uma única classe.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "Assinatura de índice ausente no tipo '{0}'.", "Index_signatures_are_incompatible_2330": "As assinaturas de índice são incompatíveis.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Todas as declarações individuais na declaração mesclada '{0}' devem ser exportadas ou ficar no local.", + "Infer_parameter_types_from_usage_95012": "Inferir os tipos de parâmetro do uso.", + "Infer_type_of_0_from_usage_95011": "Inferir o tipo de '{0}' do uso.", "Initialize_property_0_in_the_constructor_90020": "Inicializar a propriedade '{0}' no construtor.", "Initialize_static_property_0_90021": "Inicializar a propriedade estática '{0}'.", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "O inicializador da variável de membro de instância '{0}' não pode referenciar o identificador '{1}' declarado no construtor.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "Uso inválido de '{0}' no modo estrito.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor inválido para 'jsxFactory'. '{0}' não é um identificador válido ou nome qualificado.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor inválido para '--reactNamespace'. '{0}' não é um identificador válido.", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "JSDoc \"@augments {0}\" não corresponde à cláusula \"extends {1}\".", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "JSDoc \"@augments\" não está anexado à declaração de classe.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "O '@{0} {1}' do JSDoc não corresponde à cláusula 'extends {2}'.", + "JSDoc_0_is_not_attached_to_a_class_8022": "O '@{0}' do JSDoc não está anexado a uma classe.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "A marcação do JSDoc \"@param\" tem o nome \"{0}\", mas não há nenhum parâmetro com esse nome.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "A marca JSDoc \"@typedef\" deve ter uma anotação de tipo ou ser seguida pelas marcas \"@property\" or \"@member\".", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Os tipos de JSDoc podem ser usados somente dentro dos comentários de documentação.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "O tipo de elementos iterados de um operando \"yield*\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "O tipo do operando \"yield\" em um gerador assíncrono deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", "Type_parameter_0_has_a_circular_constraint_2313": "O parâmetro de tipo '{0}' tem uma restrição circular.", + "Type_parameter_0_has_a_circular_default_2716": "O parâmetro de tipo '{0}' tem um padrão circular.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "O parâmetro de tipo '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome particular '{1}'.", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "O parâmetro de tipo '{0}' da assinatura de construtor da interface exportada tem ou está usando o nome particular '{1}'.", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "O parâmetro de tipo '{0}' da classe exportada tem ou está usando o nome particular '{1}'.", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "Observe os arquivos de entrada.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' são especificados duas vezes. O atributo chamado '{0}' será substituído.", "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' só pode ser usado em um arquivo .ts.", "_0_expected_1005": "'{0}' esperado.", diff --git a/lib/rus/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json similarity index 99% rename from lib/rus/diagnosticMessages.generated.json rename to lib/ru/diagnosticMessages.generated.json index 5da79e4c3fff4..4ac7173a9b657 100644 --- a/lib/rus/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "Выражение yield разрешено использовать только в теле генератора.", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "Невозможно получить доступ к абстрактному методу \"{0}\" класса \"{1}\" с помощью выражения super.", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "Абстрактные методы могут использоваться только в абстрактных классах.", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "Абстрактное свойство \"{0}\" в классе \"{1}\" недоступно в конструкторе.", "Accessibility_modifier_already_seen_1028": "Модификатор специальных возможностей уже встречался.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Методы доступа доступны только при разработке для ECMAScript 5 и более поздних версий.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Методы доступа должны быть абстрактными или неабстрактными.", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Элемент объекта не может быть объявлен необязательным.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "Сигнатура перегрузки не может быть объявлена в качестве генератора.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Унарное выражение с оператором \"{0}\" не допускается в левой части выражения, возводимого в степень. Попробуйте заключить выражение в скобки.", + "Annotate_with_type_from_JSDoc_95009": "Заметка с типом из JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Заметки с типами из JSDoc", "Argument_expression_expected_1135": "Ожидалось выражение аргумента.", "Argument_for_0_option_must_be_Colon_1_6046": "Аргумент для параметра \"{0}\" должен быть {1}.", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "Аргумент типа \"{0}\" нельзя назначить параметру типа \"{1}\".", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "Ожидался бит.", "Binding_element_0_implicitly_has_an_1_type_7031": "Элемент привязки \"{0}\" имеет неявный тип \"{1}\".", "Block_scoped_variable_0_used_before_its_declaration_2448": "Переменная \"{0}\" с областью видимости, ограниченной блоком, использована перед своим объявлением.", + "Call_decorator_expression_90028": "Вызов выражения-декоратора.", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Сигнатура вызова, у которой нет аннотации типа возвращаемого значения, неявно имеет тип возвращаемого значения any.", "Call_target_does_not_contain_any_signatures_2346": "Объект вызова не содержит сигнатуры.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Не удается получить доступ к {0}.{1}, так как {0} является типом, но не является пространством имен. Вы хотели получить тип свойства {1} в {0} с использованием {0}[\"{1}\"]?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Не удается записать файл \"{0}\", так как это привело бы к перезаписи входного файла.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Переменная оператора catch не может иметь аннотацию типа.", "Catch_clause_variable_cannot_have_an_initializer_1197": "Переменная оператора catch не может иметь инициализатор.", - "Change_0_to_1_90014": "Измените {0} на {1}.", + "Change_0_to_1_90014": "Замена \"{0}\" на \"{1}\".", "Change_extends_to_implements_90003": "Измените \"extends\" на \"implements\".", "Change_spelling_to_0_90022": "Изменить правописание на \"{0}\".", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Идет проверка того, является ли \"{0}\" самым длинным соответствующим префиксом для \"{1}\" — \"{2}\".", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "Класс \"{0}\" неправильно расширяет базовый класс \"{1}\".", "Class_0_incorrectly_implements_interface_1_2420": "Класс \"{0}\" неправильно реализует интерфейс \"{1}\".", "Class_0_used_before_its_declaration_2449": "Класс \"{0}\" использован прежде, чем объявлен.", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "В объявлении класса не может использоваться более одного тега \"@augments\" или \"@extends\".", "Class_name_cannot_be_0_2414": "Имя класса не может иметь значение \"{0}\".", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "Статическая сторона класса \"{0}\" неправильно расширяет статическую сторону базового класса \"{1}\".", "Classes_can_only_extend_a_single_class_1174": "Классы могут расширить только один класс.", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "В типе \"{0}\" отсутствует сигнатура индекса.", "Index_signatures_are_incompatible_2330": "Сигнатуры индекса несовместимы.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Все отдельные объявления в объединенном объявлении \"{0}\" должны быть экспортированными или локальными.", + "Infer_parameter_types_from_usage_95012": "Вывод типов параметров на основе использования.", + "Infer_type_of_0_from_usage_95011": "Вывод типа \"{0}\" на основе использования.", "Initialize_property_0_in_the_constructor_90020": "Инициализировать свойство \"{0}\" в конструкторе.", "Initialize_static_property_0_90021": "Инициализировать статическое свойство \"{0}\".", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Инициализатор переменной-элемента экземпляра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный в конструкторе.", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "Недопустимое использование \"{0}\" в строгом режиме.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Недопустимое значение для jsxFactory. \"{0}\" не является допустимым идентификатором или полным именем.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Недопустимое значение для \"--reactNamespace\". \"{0}\" не является допустимым идентификатором.", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "Параметр \"@augments {0}\" JSDoc не соответствует предложению \"extends {1}\".", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "Параметр \"@augments\" JSDoc не связан с объявлением класса.", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Параметр \"@{0} {1}\" JSDoc не соответствует предложению \"extends {2}\".", + "JSDoc_0_is_not_attached_to_a_class_8022": "Параметр \"@{0}\" JSDoc не связан с классом.", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "У тега \"@param\" JSDoc есть имя \"{0}\", но параметр с таким именем отсутствует.", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "У тега \"@typedef\" JSDoc должна быть аннотация типа, или после него должны стоять теги \"@property\" или \"@member\".", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Типы JSDoc можно использовать только в комментариях в документации.", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Тип элементов итерации для операнда \"yield*\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Тип операнда \"yield\" в асинхронном генераторе должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", "Type_parameter_0_has_a_circular_constraint_2313": "Параметр типа \"{0}\" содержит циклическое ограничение.", + "Type_parameter_0_has_a_circular_default_2716": "Параметр типа \"{0}\" по умолчанию является циклическим.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Параметр типа \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Параметр типа \"{0}\" сигнатуры конструктора из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Параметр типа \"{0}\" экспортированного класса имеет или использует закрытое имя \"{1}\".", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "Просмотр входных файлов.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Невозможно переименовать элементы, определенные в стандартной библиотеке TypeScript.", "You_cannot_rename_this_element_8000": "Этот элемент переименовать нельзя.", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" принимает слишком мало аргументов для использования в качестве декоратора. Вы хотели сначала вызвать его и записать \"@{0}()\"?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" указаны дважды. Атрибут \"{0}\" будет перезаписан.", "_0_can_only_be_used_in_a_ts_file_8009": "\"{0}\" может использоваться только в TS-файле.", "_0_expected_1005": "Ожидалось \"{0}\".", diff --git a/lib/trk/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json similarity index 100% rename from lib/trk/diagnosticMessages.generated.json rename to lib/tr/diagnosticMessages.generated.json diff --git a/lib/tsc.js b/lib/tsc.js index 3eccc63708f33..e7cd2feb24d17 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -165,8 +165,8 @@ var ts; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { var map = Object.create(null); - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } function createMap() { @@ -287,6 +287,16 @@ var ts; return undefined; } ts.forEach = forEach; + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -340,6 +350,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i], i)) { @@ -1064,6 +1084,15 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2264,6 +2293,14 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -2406,8 +2443,13 @@ var ts; if (parentResult) { var baseName = getBaseNameOfFileName(fileOrDirectory); if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, baseName, host.fileExists(fileOrDirectoryPath)); - updateFileSystemEntry(parentResult.directories, baseName, host.directoryExists(fileOrDirectoryPath)); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + updateFileSystemEntry(parentResult.directories, baseName, fsQueryResult.directoryExists); + return fsQueryResult; } } } @@ -2465,7 +2507,7 @@ var ts; var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); var fileWatcherCallbacks = ts.createMultiMap(); @@ -2819,7 +2861,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -3774,9 +3816,9 @@ var ts; Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), 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: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "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: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\"."), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\"."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), @@ -5814,6 +5856,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 238: + case 237: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -6542,6 +6594,14 @@ var ts; return node && !!(node.flags & 1048576); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 || node.typeArguments[0].kind === 133); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 181) { return false; @@ -6561,6 +6621,10 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(string, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, string).charCodeAt(0) === 34; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; function isDeclarationOfFunctionOrClassExpression(s) { if (s.valueDeclaration && s.valueDeclaration.kind === 226) { var declaration = s.valueDeclaration; @@ -15088,8 +15152,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -15161,8 +15225,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -18795,6 +18859,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); } @@ -18837,18 +18902,25 @@ var ts; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); } } - return moduleName; + return packageName; } function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); @@ -19189,6 +19261,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); + var ambientModulesCache; var patternAmbientModules; var globalObjectType; var globalFunctionType; @@ -24529,13 +24602,11 @@ var ts; function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -25302,7 +25373,7 @@ var ts; } var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); spread.flags |= propagatedFlags; - spread.flags |= 1048576; + spread.flags |= 1048576 | 4194304; spread.objectFlags |= 128; spread.symbol = symbol; return spread; @@ -28056,6 +28127,14 @@ var ts; return 8388607; } function getTypeWithFacts(type, include) { + if (type.flags & 524288) { + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -30730,7 +30809,7 @@ var ts; return unknownType; } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); + markPropertyAsReferenced(prop, node, left.kind === 99); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -30879,12 +30958,18 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -33763,7 +33848,9 @@ var ts; if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; if (!symbol) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; @@ -34856,7 +34943,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, undefined); + markPropertyAsReferenced(property, undefined, false); if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -38663,13 +38750,15 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -56580,14 +56669,14 @@ var ts; var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); ts.mutateMap(missingFileWatches, newMissingFilePathMap, { createNewValue: createMissingFileWatch, - onDeleteValue: ts.closeFileWatcher + onDeleteValue: closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { createNewValue: createWildcardDirectoryWatcher, - onDeleteValue: ts.closeFileWatcherOf, + onDeleteValue: closeFileWatcherOf, onExistingValue: updateWildcardDirectoryWatcher }); function createWildcardDirectoryWatcher(directory, flags) { @@ -56605,8 +56694,6 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; -})(ts || (ts = {})); -(function (ts) { function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -56683,40 +56770,26 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; - var emittedSourceFiles; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - if (!isDetailed) { - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - } - return { - outputFiles: outputFiles, - emitSkipped: emitResult.emitSkipped, - diagnostics: emitResult.diagnostics, - sourceMaps: emitResult.sourceMaps, - emittedSourceFiles: emittedSourceFiles - }; - function writeFile(fileName, text, writeByteOrderMark, _onError, sourceFiles) { + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - if (isDetailed) { - emittedSourceFiles = ts.addRange(emittedSourceFiles, sourceFiles); - } } } ts.getFileEmitOutput = getFileEmitOutput; -})(ts || (ts = {})); -(function (ts) { function createBuilder(options) { var isModuleEmit; var fileInfos = ts.createMap(); var semanticDiagnosticsPerFile = ts.createMap(); - var changedFileNames = ts.createMap(); + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; var emitHandler; return { updateProgram: updateProgram, getFilesAffectedBy: getFilesAffectedBy, - emitFile: emitFile, emitChangedFiles: emitChangedFiles, getSemanticDiagnostics: getSemanticDiagnostics, clear: clear @@ -56729,33 +56802,36 @@ var ts; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, onDeleteValue: removeExistingFileInfo, onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } }); } - function registerChangedFile(path, fileName) { - changedFileNames.set(path, fileName); + function registerChangedFile(path) { + changedFilesSet.set(path, true); semanticDiagnosticsPerFile.delete(path); } function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); emitHandler.onAddSourceFile(program, sourceFile); - return { fileName: sourceFile.fileName, version: sourceFile.version, signature: undefined }; + return { version: sourceFile.version, signature: undefined }; } - function removeExistingFileInfo(existingFileInfo, path) { - registerChangedFile(path, existingFileInfo.fileName); + function removeExistingFileInfo(_existingFileInfo, path) { + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); emitHandler.onRemoveSourceFile(path); } function updateExistingFileInfo(program, existingInfo, sourceFile) { if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); } } function ensureProgramGraph(program) { @@ -56770,87 +56846,73 @@ var ts; } function getFilesAffectedBy(program, path) { ensureProgramGraph(program); - var sourceFile = program.getSourceFile(path); - var singleFileResult = sourceFile && options.shouldEmitFile(sourceFile) ? [sourceFile.fileName] : []; - var info = fileInfos.get(path); - if (!info || !updateShapeSignature(program, sourceFile, info)) { - return singleFileResult; + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; } - ts.Debug.assert(!!sourceFile); - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult); + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); } - function emitFile(program, path) { + function emitChangedFiles(program, writeFileCallback) { ensureProgramGraph(program); - if (!fileInfos.has(path)) { - return { outputFiles: [], emitSkipped: true }; + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(undefined, writeFileCallback)]; } - return options.getEmitOutput(program, program.getSourceFileByPath(path), false, false); - } - function enumerateChangedFilesSet(program, onChangedFile, onAffectedFile) { - changedFileNames.forEach(function (fileName, path) { - onChangedFile(fileName, path); - var affectedFiles = getFilesAffectedBy(program, path); - for (var _i = 0, affectedFiles_1 = affectedFiles; _i < affectedFiles_1.length; _i++) { - var file = affectedFiles_1[_i]; - onAffectedFile(file, program.getSourceFile(file)); - } - }); - } - function enumerateChangedFilesEmitOutput(program, emitOnlyDtsFiles, onChangedFile, onEmitOutput) { var seenFiles = ts.createMap(); - enumerateChangedFilesSet(program, onChangedFile, function (fileName, sourceFile) { - if (!seenFiles.has(fileName)) { - seenFiles.set(fileName, true); - if (sourceFile) { - semanticDiagnosticsPerFile.delete(sourceFile.path); - var emitOutput = options.getEmitOutput(program, sourceFile, emitOnlyDtsFiles, true); - onEmitOutput(emitOutput, sourceFile); - if (emitOutput.emittedSourceFiles) { - for (var _i = 0, _a = emitOutput.emittedSourceFiles; _i < _a.length; _i++) { - var file = _a[_i]; - seenFiles.set(file.fileName, true); - } - } + var result; + changedFilesSet.forEach(function (_true, path) { + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); } - } + }); }); - } - function emitChangedFiles(program) { - ensureProgramGraph(program); - var result = []; - enumerateChangedFilesEmitOutput(program, false, ts.noop, function (emitOutput) { return result.push(emitOutput); }); - changedFileNames.clear(); - return result; + changedFilesSet.clear(); + return result || ts.emptyArray; } function getSemanticDiagnostics(program, cancellationToken) { ensureProgramGraph(program); - enumerateChangedFilesSet(program, ts.noop, function (_affectedFileName, sourceFile) { - if (sourceFile) { - semanticDiagnosticsPerFile.delete(sourceFile.path); - } - }); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + return program.getSemanticDiagnostics(undefined, cancellationToken); + } var diagnostics; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - if (cachedDiagnostics) { - diagnostics = ts.addRange(diagnostics, cachedDiagnostics); - } - else { - var cachedDiagnostics_1 = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, cachedDiagnostics_1); - diagnostics = ts.addRange(diagnostics, cachedDiagnostics_1); - } + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); } return diagnostics || ts.emptyArray; } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } function clear() { isModuleEmit = undefined; emitHandler = undefined; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); - changedFileNames.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); } function containsOnlyAmbientModules(sourceFile) { for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -56861,15 +56923,22 @@ var ts; } return true; } - function updateShapeSignature(program, sourceFile, info) { + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { - latestSignature = options.computeHash(sourceFile.text); + latestSignature = sourceFile.version; info.signature = latestSignature; } else { - var emitOutput = options.getEmitOutput(program, sourceFile, true, false); + var emitOutput = getFileEmitOutput(program, sourceFile, true); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = options.computeHash(emitOutput.outputFiles[0].text); info.signature = latestSignature; @@ -56921,21 +56990,23 @@ var ts; referencedFiles.set(referencedPath, true); } } - function getAllEmittableFiles(program, firstSourceFile) { - var defaultLibraryFileName = ts.getDefaultLibFileName(program.getCompilerOptions()); - var sourceFiles = program.getSourceFiles(); - var result = []; - add(firstSourceFile); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; if (sourceFile !== firstSourceFile) { - add(sourceFile); + addSourceFile(sourceFile); } } - return result; - function add(sourceFile) { - if (ts.getBaseFileName(sourceFile.fileName) !== defaultLibraryFileName && options.shouldEmitFile(sourceFile)) { - result.push(sourceFile.fileName); + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); } } } @@ -56947,12 +57018,12 @@ var ts; onUpdateSourceFileWithSameVersion: ts.returnFalse, getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape }; - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { var options = program.getCompilerOptions(); if (options && (options.out || options.outFile)) { - return singleFileResult; + return [sourceFile]; } - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } } function getModuleEmitHandler() { @@ -56997,7 +57068,7 @@ var ts; if (referencesInFile.has(removedFilePath)) { var referencedByInfo = fileInfos.get(filePath); if (referencedByInfo) { - registerChangedFile(filePath, referencedByInfo.fileName); + registerChangedFile(filePath); } } }); @@ -57009,29 +57080,26 @@ var ts; return referencesInFile.has(referencedFilePath) ? filePath : undefined; }); } - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } var compilerOptions = program.getCompilerOptions(); if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return singleFileResult; + return [sourceFile]; } var seenFileNamesMap = ts.createMap(); - var setSeenFileName = function (path, sourceFile) { - seenFileNamesMap.set(path, sourceFile && options.shouldEmitFile(sourceFile) ? sourceFile.fileName : undefined); - }; var path = sourceFile.path; - setSeenFileName(path, sourceFile); + seenFileNamesMap.set(path, sourceFile); var queue = getReferencedByPaths(path); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = program.getSourceFileByPath(currentPath); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile, fileInfos.get(currentPath))) { + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { queue.push.apply(queue, getReferencedByPaths(currentPath)); } - setSeenFileName(currentPath, currentSourceFile); } } return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); @@ -57928,7 +57996,8 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 || sourceFile.scriptKind === 4 || + sourceFile.scriptKind === 5 || ts.isCheckJsEnabledForFile(sourceFile, options); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -58495,8 +58564,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var file = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var file = sourceFiles_2[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -58507,8 +58576,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -58989,6 +59058,24 @@ var ts; function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, dirPath.charCodeAt(0) === 47 ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; @@ -59000,7 +59087,7 @@ var ts; dirPath = ts.getDirectoryPath(dirPath); } if (isNodeModulesDirectory(dirPath)) { - return { dir: dir, dirPath: dirPath }; + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { @@ -59012,7 +59099,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return { dir: dir, dirPath: dirPath }; + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -59042,13 +59129,15 @@ var ts; var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } - var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath; - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; - } - else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + } } } } @@ -59072,9 +59161,11 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); } } - var dirPath = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath).dirPath; - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - dirWatcher.refCount--; + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; + } } } function createDirectoryWatcher(directory, dirPath) { @@ -59176,7 +59267,7 @@ var ts; closeTypeRootsWatch(); return; } - var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: ts.returnTrue, getCurrentDirectory: getCurrentDirectory }); + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); if (typeRoots) { ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { createNewValue: createTypeRootsWatch, @@ -59187,6 +59278,11 @@ var ts; closeTypeRootsWatch(); } } + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); @@ -59304,7 +59400,8 @@ var ts; var diagnostics = program.getSyntacticDiagnostics().slice(); var reportSemanticDiagnostics = false; if (diagnostics.length === 0) { - diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === 0) { reportSemanticDiagnostics = true; } @@ -59312,7 +59409,7 @@ var ts; var emittedFiles = program.getCompilerOptions().listEmittedFiles ? [] : undefined; var sourceMaps; var emitSkipped; - var result = builder.emitChangedFiles(program); + var result = builder.emitChangedFiles(program, writeFile); if (result.length === 0) { emitSkipped = true; } @@ -59322,13 +59419,12 @@ var ts; if (emitOutput.emitSkipped) { emitSkipped = true; } - diagnostics = ts.concatenate(diagnostics, emitOutput.diagnostics); + ts.addRange(diagnostics, emitOutput.diagnostics); sourceMaps = ts.concatenate(sourceMaps, emitOutput.sourceMaps); - writeOutputFiles(emitOutput.outputFiles); } } if (reportSemanticDiagnostics) { - diagnostics = diagnostics.concat(builder.getSemanticDiagnostics(program)); + ts.addRange(diagnostics, builder.getSemanticDiagnostics(program)); } return handleEmitOutputAndReportErrors(host, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic); function ensureDirectoriesExist(directoryPath) { @@ -59338,29 +59434,20 @@ var ts; host.createDirectory(directoryPath); } } - function writeFile(fileName, data, writeByteOrderMark) { + function writeFile(fileName, text, writeByteOrderMark, onError) { try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, data, writeByteOrderMark); + host.writeFile(fileName, text, writeByteOrderMark); ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + if (emittedFiles) { + emittedFiles.push(fileName); + } } catch (e) { - return ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, e); - } - } - function writeOutputFiles(outputFiles) { - if (outputFiles) { - for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { - var outputFile = outputFiles_1[_i]; - var error = writeFile(outputFile.name, outputFile.text, outputFile.writeByteOrderMark); - if (error) { - diagnostics.push(error); - } - if (emittedFiles) { - emittedFiles.push(outputFile.name); - } + if (onError) { + onError(e.message); } } } @@ -59437,7 +59524,7 @@ var ts; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, getCurrentDirectory())) : getCurrentDirectory()); - var builder = ts.createBuilder({ getCanonicalFileName: getCanonicalFileName, getEmitOutput: ts.getFileEmitOutput, computeHash: computeHash, shouldEmitFile: function () { return true; } }); + var builder = ts.createBuilder({ getCanonicalFileName: getCanonicalFileName, computeHash: computeHash }); synchronizeProgram(); watchConfigFileWildCardDirectories(); return function () { return program; }; @@ -59658,18 +59745,24 @@ var ts; return watchDirectory(directory, function (fileOrDirectory) { ts.Debug.assert(!!configFileName); var fileOrDirectoryPath = toPath(fileOrDirectory); - directoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - removeSourceFile(fileOrDirectoryPath); + var result = directoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); + if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { + hostSourceFile.version++; + } + else { + removeSourceFile(fileOrDirectoryPath); + } if (fileOrDirectoryPath !== directory && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } if (!needsReload) { - var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, directoryStructureHost); - if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { + var result_6 = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, directoryStructureHost); + if (!configFileSpecs.filesSpecs && result_6.fileNames.length === 0) { reportDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); } - rootFileNames = result.fileNames; + rootFileNames = result_6.fileNames; scheduleProgramUpdate(); } }, flags); @@ -60701,7 +60794,7 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { @@ -60896,9 +60989,9 @@ var ts; }; function getFileNames() { var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - filesSpecs = raw["files"]; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } @@ -60908,25 +61001,25 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } @@ -60996,7 +61089,7 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { @@ -61112,7 +61205,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } diff --git a/lib/tsserver.js b/lib/tsserver.js index ae65dfcde7170..59ffe06fde749 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1190,8 +1190,8 @@ var ts; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { var map = Object.create(null); - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } function createMap() { @@ -1318,6 +1318,16 @@ var ts; return undefined; } ts.forEach = forEach; + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1371,6 +1381,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i], i)) { @@ -2095,6 +2115,15 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -3309,6 +3338,14 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3451,8 +3488,13 @@ var ts; if (parentResult) { var baseName = getBaseNameOfFileName(fileOrDirectory); if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, baseName, host.fileExists(fileOrDirectoryPath)); - updateFileSystemEntry(parentResult.directories, baseName, host.directoryExists(fileOrDirectoryPath)); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + updateFileSystemEntry(parentResult.directories, baseName, fsQueryResult.directoryExists); + return fsQueryResult; } } } @@ -3510,7 +3552,7 @@ var ts; var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); var fileWatcherCallbacks = ts.createMultiMap(); @@ -3869,7 +3911,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -4824,9 +4866,9 @@ var ts; Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), 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: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "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: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\"."), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\"."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), @@ -5549,6 +5591,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); } @@ -5591,18 +5634,25 @@ var ts; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); } } - return moduleName; + return packageName; } function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); @@ -6082,6 +6132,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 238: + case 237: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -6810,6 +6870,14 @@ var ts; return node && !!(node.flags & 1048576); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 || node.typeArguments[0].kind === 133); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 181) { return false; @@ -6829,6 +6897,10 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(string, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, string).charCodeAt(0) === 34; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; function isDeclarationOfFunctionOrClassExpression(s) { if (s.valueDeclaration && s.valueDeclaration.kind === 226) { var declaration = s.valueDeclaration; @@ -17037,8 +17109,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -17110,8 +17182,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -20345,6 +20417,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); + var ambientModulesCache; var patternAmbientModules; var globalObjectType; var globalFunctionType; @@ -25764,13 +25837,11 @@ var ts; function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -26537,7 +26608,7 @@ var ts; } var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); spread.flags |= propagatedFlags; - spread.flags |= 1048576; + spread.flags |= 1048576 | 4194304; spread.objectFlags |= 128; spread.symbol = symbol; return spread; @@ -29298,6 +29369,14 @@ var ts; return 8388607; } function getTypeWithFacts(type, include) { + if (type.flags & 524288) { + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -31972,7 +32051,7 @@ var ts; return unknownType; } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); + markPropertyAsReferenced(prop, node, left.kind === 99); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -32121,12 +32200,18 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -35012,7 +35097,9 @@ var ts; if (produceDiagnostics) { var symbol = getNodeLinks(node).resolvedSymbol; if (!symbol) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 && getSymbolLinks(symbol).typeParameters; @@ -36112,7 +36199,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, undefined); + markPropertyAsReferenced(property, undefined, false); if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -39919,13 +40006,15 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -58071,40 +58160,26 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; - var emittedSourceFiles; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - if (!isDetailed) { - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - } - return { - outputFiles: outputFiles, - emitSkipped: emitResult.emitSkipped, - diagnostics: emitResult.diagnostics, - sourceMaps: emitResult.sourceMaps, - emittedSourceFiles: emittedSourceFiles - }; - function writeFile(fileName, text, writeByteOrderMark, _onError, sourceFiles) { + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - if (isDetailed) { - emittedSourceFiles = ts.addRange(emittedSourceFiles, sourceFiles); - } } } ts.getFileEmitOutput = getFileEmitOutput; -})(ts || (ts = {})); -(function (ts) { function createBuilder(options) { var isModuleEmit; var fileInfos = ts.createMap(); var semanticDiagnosticsPerFile = ts.createMap(); - var changedFileNames = ts.createMap(); + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; var emitHandler; return { updateProgram: updateProgram, getFilesAffectedBy: getFilesAffectedBy, - emitFile: emitFile, emitChangedFiles: emitChangedFiles, getSemanticDiagnostics: getSemanticDiagnostics, clear: clear @@ -58117,33 +58192,36 @@ var ts; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, onDeleteValue: removeExistingFileInfo, onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } }); } - function registerChangedFile(path, fileName) { - changedFileNames.set(path, fileName); + function registerChangedFile(path) { + changedFilesSet.set(path, true); semanticDiagnosticsPerFile.delete(path); } function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); emitHandler.onAddSourceFile(program, sourceFile); - return { fileName: sourceFile.fileName, version: sourceFile.version, signature: undefined }; + return { version: sourceFile.version, signature: undefined }; } - function removeExistingFileInfo(existingFileInfo, path) { - registerChangedFile(path, existingFileInfo.fileName); + function removeExistingFileInfo(_existingFileInfo, path) { + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); emitHandler.onRemoveSourceFile(path); } function updateExistingFileInfo(program, existingInfo, sourceFile) { if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); } } function ensureProgramGraph(program) { @@ -58158,87 +58236,73 @@ var ts; } function getFilesAffectedBy(program, path) { ensureProgramGraph(program); - var sourceFile = program.getSourceFile(path); - var singleFileResult = sourceFile && options.shouldEmitFile(sourceFile) ? [sourceFile.fileName] : []; - var info = fileInfos.get(path); - if (!info || !updateShapeSignature(program, sourceFile, info)) { - return singleFileResult; + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; } - ts.Debug.assert(!!sourceFile); - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult); + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); } - function emitFile(program, path) { + function emitChangedFiles(program, writeFileCallback) { ensureProgramGraph(program); - if (!fileInfos.has(path)) { - return { outputFiles: [], emitSkipped: true }; + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(undefined, writeFileCallback)]; } - return options.getEmitOutput(program, program.getSourceFileByPath(path), false, false); - } - function enumerateChangedFilesSet(program, onChangedFile, onAffectedFile) { - changedFileNames.forEach(function (fileName, path) { - onChangedFile(fileName, path); - var affectedFiles = getFilesAffectedBy(program, path); - for (var _i = 0, affectedFiles_1 = affectedFiles; _i < affectedFiles_1.length; _i++) { - var file = affectedFiles_1[_i]; - onAffectedFile(file, program.getSourceFile(file)); - } - }); - } - function enumerateChangedFilesEmitOutput(program, emitOnlyDtsFiles, onChangedFile, onEmitOutput) { var seenFiles = ts.createMap(); - enumerateChangedFilesSet(program, onChangedFile, function (fileName, sourceFile) { - if (!seenFiles.has(fileName)) { - seenFiles.set(fileName, true); - if (sourceFile) { - semanticDiagnosticsPerFile.delete(sourceFile.path); - var emitOutput = options.getEmitOutput(program, sourceFile, emitOnlyDtsFiles, true); - onEmitOutput(emitOutput, sourceFile); - if (emitOutput.emittedSourceFiles) { - for (var _i = 0, _a = emitOutput.emittedSourceFiles; _i < _a.length; _i++) { - var file = _a[_i]; - seenFiles.set(file.fileName, true); - } - } + var result; + changedFilesSet.forEach(function (_true, path) { + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); } - } + }); }); - } - function emitChangedFiles(program) { - ensureProgramGraph(program); - var result = []; - enumerateChangedFilesEmitOutput(program, false, ts.noop, function (emitOutput) { return result.push(emitOutput); }); - changedFileNames.clear(); - return result; + changedFilesSet.clear(); + return result || ts.emptyArray; } function getSemanticDiagnostics(program, cancellationToken) { ensureProgramGraph(program); - enumerateChangedFilesSet(program, ts.noop, function (_affectedFileName, sourceFile) { - if (sourceFile) { - semanticDiagnosticsPerFile.delete(sourceFile.path); - } - }); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + return program.getSemanticDiagnostics(undefined, cancellationToken); + } var diagnostics; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - if (cachedDiagnostics) { - diagnostics = ts.addRange(diagnostics, cachedDiagnostics); - } - else { - var cachedDiagnostics_1 = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, cachedDiagnostics_1); - diagnostics = ts.addRange(diagnostics, cachedDiagnostics_1); - } + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); } return diagnostics || ts.emptyArray; } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } function clear() { isModuleEmit = undefined; emitHandler = undefined; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); - changedFileNames.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); } function containsOnlyAmbientModules(sourceFile) { for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -58249,15 +58313,22 @@ var ts; } return true; } - function updateShapeSignature(program, sourceFile, info) { + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { - latestSignature = options.computeHash(sourceFile.text); + latestSignature = sourceFile.version; info.signature = latestSignature; } else { - var emitOutput = options.getEmitOutput(program, sourceFile, true, false); + var emitOutput = getFileEmitOutput(program, sourceFile, true); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = options.computeHash(emitOutput.outputFiles[0].text); info.signature = latestSignature; @@ -58309,21 +58380,23 @@ var ts; referencedFiles.set(referencedPath, true); } } - function getAllEmittableFiles(program, firstSourceFile) { - var defaultLibraryFileName = ts.getDefaultLibFileName(program.getCompilerOptions()); - var sourceFiles = program.getSourceFiles(); - var result = []; - add(firstSourceFile); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; if (sourceFile !== firstSourceFile) { - add(sourceFile); + addSourceFile(sourceFile); } } - return result; - function add(sourceFile) { - if (ts.getBaseFileName(sourceFile.fileName) !== defaultLibraryFileName && options.shouldEmitFile(sourceFile)) { - result.push(sourceFile.fileName); + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); } } } @@ -58335,12 +58408,12 @@ var ts; onUpdateSourceFileWithSameVersion: ts.returnFalse, getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape }; - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { var options = program.getCompilerOptions(); if (options && (options.out || options.outFile)) { - return singleFileResult; + return [sourceFile]; } - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } } function getModuleEmitHandler() { @@ -58385,7 +58458,7 @@ var ts; if (referencesInFile.has(removedFilePath)) { var referencedByInfo = fileInfos.get(filePath); if (referencedByInfo) { - registerChangedFile(filePath, referencedByInfo.fileName); + registerChangedFile(filePath); } } }); @@ -58397,29 +58470,26 @@ var ts; return referencesInFile.has(referencedFilePath) ? filePath : undefined; }); } - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } var compilerOptions = program.getCompilerOptions(); if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return singleFileResult; + return [sourceFile]; } var seenFileNamesMap = ts.createMap(); - var setSeenFileName = function (path, sourceFile) { - seenFileNamesMap.set(path, sourceFile && options.shouldEmitFile(sourceFile) ? sourceFile.fileName : undefined); - }; var path = sourceFile.path; - setSeenFileName(path, sourceFile); + seenFileNamesMap.set(path, sourceFile); var queue = getReferencedByPaths(path); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = program.getSourceFileByPath(currentPath); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile, fileInfos.get(currentPath))) { + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { queue.push.apply(queue, getReferencedByPaths(currentPath)); } - setSeenFileName(currentPath, currentSourceFile); } } return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); @@ -59321,7 +59391,8 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 || sourceFile.scriptKind === 4 || + sourceFile.scriptKind === 5 || ts.isCheckJsEnabledForFile(sourceFile, options); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -59888,8 +59959,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var file = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var file = sourceFiles_2[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -59900,8 +59971,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -61225,7 +61296,7 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { @@ -61420,9 +61491,9 @@ var ts; }; function getFileNames() { var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - filesSpecs = raw["files"]; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } @@ -61432,25 +61503,25 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } @@ -61520,7 +61591,7 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { @@ -61636,7 +61707,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -63223,9 +63294,7 @@ var ts; ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 || name.charCodeAt(0) === 39)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -63244,6 +63313,10 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -64958,18 +65031,18 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; if (sourceFile.languageVariant === 1 && location && location.parent && location.parent.kind === 252) { var tagName = location.parent.parent.openingElement.tagName; @@ -64991,14 +65064,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); } if (keywordFilters !== 0 || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); @@ -65039,7 +65112,7 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, symbolToOriginInfoMap) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { @@ -65049,6 +65122,9 @@ var ts; if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { + if (symbolToOriginInfoMap && symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, typeChecker)]) { + entry.hasAction = true; + } entries.push(entry); uniqueNames.set(id, true); } @@ -65160,47 +65236,62 @@ var ts; } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, name, allSourceFiles, host, rulesProvider) { + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (completionData) { - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral_1) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; + var symbol = ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral_1) === name; }); if (symbol) { + var codeActions = getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, rulesProvider); + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions }; } } - var keywordCompletion = ts.forEach(getKeywordCompletions(0), function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0), function (c) { return c.name === name; }); if (keywordCompletion) { return { - name: entryName, + name: name, kind: "keyword", kindModifiers: "", - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, - tags: undefined + tags: undefined, + codeActions: undefined, }; } return undefined; } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + function getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, rulesProvider) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, checker)]; + if (!symbolOriginInfo) { + return undefined; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + return ts.codefix.getCodeActionForImport(moduleSymbol, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + rulesProvider: rulesProvider, + symbolName: symbol.name, + getCanonicalFileName: ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false), + symbolToken: undefined, + kind: isDefaultExport ? 1 : 0, + }); + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName, allSourceFiles) { + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral) === entryName ? s : undefined; }); + return ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral) === entryName; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var request; var start = ts.timestamp(); @@ -65241,7 +65332,18 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; + return { + symbols: undefined, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0, + symbolToOriginInfoMap: undefined, + }; } if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -65315,6 +65417,7 @@ var ts; var isNewIdentifierLocation; var keywordFilters = 0; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } @@ -65344,7 +65447,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 279: @@ -65454,11 +65557,13 @@ var ts; ts.isStatement(scopeNode); } var symbolMeanings = 793064 | 107455 | 1920 | 2097152; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : ""); + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { if (ts.isExportAssignment(location.parent)) { return true; @@ -65511,6 +65616,47 @@ var ts; return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var symbolIdMap = ts.arrayToNumericMap(symbols, function (s) { return ts.getUniqueSymbolId(s, typeChecker); }); + ts.codefix.forEachExternalModule(typeChecker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + } + var id = ts.getUniqueSymbolId(symbol, typeChecker); + if (!symbolIdMap[id] && stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[id] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + return false; + } function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { @@ -66055,7 +66201,7 @@ var ts; return undefined; if (symbol.flags & 1920) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 || firstCharCode === 34) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { return undefined; } } @@ -66991,8 +67137,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 265) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -67021,8 +67167,8 @@ var ts; FindAllReferences.findModuleReferences = findModuleReferences; function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -67557,16 +67703,22 @@ var ts; var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, node.kind === 123, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + if (node.kind === 79) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 }, state); } else { - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; @@ -67791,8 +67943,8 @@ var ts; } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } @@ -68252,8 +68404,8 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); @@ -69152,6 +69304,60 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + 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 = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var MaxPackageNameLength = 214; + function validatePackageName(packageName) { + if (!packageName) { + return 2; + } + if (packageName.length > MaxPackageNameLength) { + return 3; + } + if (packageName.charCodeAt(0) === 46) { + return 4; + } + if (packageName.charCodeAt(0) === 95) { + return 5; + } + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6; + } + return 0; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2: + return "Package name '" + typing + "' cannot be empty"; + case 3: + return "Package name '" + typing + "' should be less than " + MaxPackageNameLength + " characters"; + case 4: + return "Package name '" + typing + "' cannot start with '.'"; + case 5: + return "Package name '" + typing + "' cannot start with '_'"; + case 1: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0: + throw ts.Debug.fail(); + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; @@ -69170,8 +69376,8 @@ var ts; getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var sourceFile = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); @@ -74179,22 +74385,22 @@ var ts; var textChanges; (function (textChanges) { function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -74278,6 +74484,11 @@ var ts; ChangeTracker.fromContext = function (context) { return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.rulesProvider); }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; @@ -75081,6 +75292,40 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_module_0.code, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: "Install '" + typesPackageName + "'", + changes: [], + commands: [{ type: "install package", packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -75480,6 +75725,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -75568,413 +75814,424 @@ var ts; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName_2; - if (umdSymbol.flags & 2097152) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName_2 = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455)); - symbolName_2 = symbol.name; + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + rulesProvider: context.rulesProvider, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbol, context) { + var declarations = getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + var actions = []; + if (context.symbolToken) { + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } + } + } + actions.push(getCodeActionForAddImport(moduleSymbol, context, declarations)); + return actions; + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 238) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 240 ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { + return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; + }); + } + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238: + return parent; + case 248: + return parent.parent; + default: + ts.Debug.assert(parent.kind === 244); + return undefined; + } + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var importDecl = ts.createImportDeclaration(undefined, undefined, createImportClauseOfKind(kind, symbolName), createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - return getCodeActionForImport(symbol, symbolName_2, false, true); + }); + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + switch (kind) { + case 1: + return ts.createImportClause(ts.createIdentifier(symbolName), undefined); + case 2: + return ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))); + case 0: + return ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); + default: + ts.Debug.assertNever(kind); } - var candidateModules = 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)) { - candidateModules.push(otherSourceFile.symbol); - } + } + function getModuleSpecifierForNewImport(sourceFile, moduleSymbol, options, getCanonicalFileName, host) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + return tryGetModuleNameFromAmbientModule(moduleSymbol) || + tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) || + tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) || + tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) || + options.rootDirs && tryGetModuleNameFromRootDirs(options.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName)); + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_1[_a]; - context.cancellationToken.throwIfCancellationRequested(); - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, true)); + } + function tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) { + if (!options.baseUrl) { + return undefined; + } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl, getCanonicalFileName); + if (!relativeName) { + return undefined; + } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + 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 || pattern === relativeNameWithIndex) { + return key; + } } } - ts.Debug.assert(name !== "default"); - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); - } } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { - return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238: - return parent; - case 248: - return parent.parent; - default: - return undefined; - } + return relativeName; + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1)); } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + return undefined; } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; + } + } + } + } + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - var existingDeclarations = getImportDeclarations(moduleSymbol); - if (existingDeclarations.length > 0) { - return getCodeActionsForExistingImport(existingDeclarations); + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + return path.substring(parts.topLevelPackageNameIndex + 1); } else { - return [getCodeActionForNewImport()]; - } - function getCodeActionsForExistingImport(declarations) { - var actions = []; - var namespaceImportDeclaration; - var namedImportDeclaration; - var existingModuleSpecifier; - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240) { - namespaceImportDeclaration = declaration; - } - else { - namedImportDeclaration = declaration; - } - existingModuleSpecifier = declaration.moduleSpecifier.getText(); - } - else { - namespaceImportDeclaration = declaration; - existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration); + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1; } - } - if (namespaceImportDeclaration) { - actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration)); - } - if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause && - (namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) { - var fileTextChanges = 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], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes)); - } - else { - actions.push(getCodeActionForNewImport(existingModuleSpecifier)); - } - return actions; - function getModuleSpecifierFromImportEqualsDeclaration(declaration) { - if (declaration.moduleReference && declaration.moduleReference.kind === 248) { - return declaration.moduleReference.expression.getText(); + break; + case 1: + case 2: + if (state === 1 && fullPath.charAt(partStart + 1) === "@") { + state = 2; } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(undefined, ts.createIdentifier(name)); - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); + else { + packageRootIndex = partEnd; + state = 3; } - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); + break; + case 3: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1; } else { - namespacePrefix = declaration.name.getText(); + state = 3; } - namespacePrefix = ts.stripQuotes(namespacePrefix); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); - } + break; } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 || statement.kind === 238) { - lastImportDeclaration = statement; - break; - } - } - } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), undefined) - : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); + } + fileNameIndex = partStart; + return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionForAddImport(moduleSymbol, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 238 && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ctx.kind, declaration.importClause); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } + } + }); + if (fromExistingImport) { + return fromExistingImport; + } + var moduleSpecifier = ts.firstDefined(declarations, moduleSpecifierFromAnyImport) + || getModuleSpecifierForNewImport(ctx.sourceFile, moduleSymbol, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return getCodeActionForNewImport(ctx, moduleSpecifier); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 238 + ? node.moduleSpecifier + : node.moduleReference.kind === 248 + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, kind, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + var name = importClause.name, namedBindings = importClause.namedBindings; + switch (kind) { + case 1: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0: { + var newImportSpecifier_1 = ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 241 && namedBindings.elements.length !== 0) { + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 241 && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - 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 || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - 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 parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } - } - } - function getNodeModulePathParts(fullPath) { - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1; - } - break; - case 1: - case 2: - if (state === 1 && fullPath.charAt(partStart + 1) === "@") { - state = 2; - } - else { - packageRootIndex = partEnd; - state = 3; - } - break; - case 3: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1; - } - else { - state = 3; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(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 getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; - } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; } + return undefined; } + case 2: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + default: + ts.Debug.assertNever(kind); } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455)); + symbolName = symbol.name; + } + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: 2 })); } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + cancellationToken.throwIfCancellationRequested(); + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.escapedName === symbolName && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(localSymbol, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 }))); + } + } + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol); + } + } + } + codefix.forEachExternalModule = forEachExternalModule; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -76635,7 +76892,7 @@ var ts; if (!usageContext.properties) { usageContext.properties = ts.createUnderscoreEscapedMap(); } - var propertyUsageContext = {}; + var propertyUsageContext = usageContext.properties.get(name) || {}; inferTypeFromContext(parent, checker, propertyUsageContext); usageContext.properties.set(name, propertyUsageContext); } @@ -76686,7 +76943,7 @@ var ts; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4, name); - symbol.type = getTypeFromUsageContext(context, checker); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); members_4.set(name, symbol); }); } @@ -76742,7 +76999,7 @@ var ts; symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); parameters.push(symbol); } - var returnType = getTypeFromUsageContext(callContext.returnType, checker); + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); return checker.createSignature(undefined, undefined, undefined, parameters, returnType, undefined, callContext.argumentTypes.length, false, false); } function addCandidateType(context, type) { @@ -76759,55 +77016,66 @@ var ts; var ts; (function (ts) { var refactor; - (function (refactor_2) { + (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { var actionName = "annotate"; var annotateTypeFromJSDoc = { name: "Annotate with type from JSDoc", description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAnnotation, - getAvailableActions: getAvailableActions - }; - var annotateFunctionFromJSDoc = { - name: "Annotate with types from JSDoc", - description: ts.Diagnostics.Annotate_with_types_from_JSDoc.message, - getEditsForAction: getEditsForFunctionAnnotation, + getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }; - refactor_2.registerRefactor(annotateTypeFromJSDoc); - refactor_2.registerRefactor(annotateFunctionFromJSDoc); + refactor.registerRefactor(annotateTypeFromJSDoc); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; } var node = ts.getTokenAtPosition(context.file, context.startPosition, false); - var decl = ts.findAncestor(node, isDeclarationWithType); - if (!decl || decl.type) { - return undefined; - } - var jsdocType = ts.getJSDocType(decl); - var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); - var refactor = (isFunctionWithJSDoc || jsdocType && decl.kind === 146) ? annotateFunctionFromJSDoc : - jsdocType ? annotateTypeFromJSDoc : - undefined; - if (refactor) { + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: refactor.name, - description: refactor.description, + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, actions: [ { - description: refactor.description, + description: annotateTypeFromJSDoc.description, name: actionName } ] }]; } } - function getEditsForAnnotation(context, action) { + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { if (actionName !== action) { return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); } + var node = ts.getTokenAtPosition(context.file, context.startPosition, false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 146) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, false); var decl = ts.findAncestor(token, isDeclarationWithType); @@ -76825,10 +77093,7 @@ var ts; renameLocation: undefined }; } - function getEditsForFunctionAnnotation(context, action) { - if (actionName !== action) { - return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); - } + function getEditsForFunctionAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, false); var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); @@ -76907,7 +77172,9 @@ var ts; case 159: return transformJSDocTypeReference(node); default: - return ts.visitEachChild(node, transformJSDocType, undefined); + var visited = ts.visitEachChild(node, transformJSDocType, undefined); + ts.setEmitFlags(visited, 1); + return visited; } } function transformJSDocOptionalType(node) { @@ -76934,6 +77201,9 @@ var ts; var name = node.typeName; var args = node.typeArguments; if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } var text = node.typeName.text; switch (node.typeName.text) { case "String": @@ -76958,7 +77228,13 @@ var ts; } return ts.createTypeReferenceNode(name, args); } - })(annotateWithTypeFromJSDoc = refactor_2.annotateWithTypeFromJSDoc || (refactor_2.annotateWithTypeFromJSDoc = {})); + function transformJSDocIndexSignature(node) { + var index = ts.createParameter(undefined, undefined, undefined, node.typeArguments[0].kind === 133 ? "n" : "s", undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 ? "number" : "string", []), undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(undefined, undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; @@ -77537,20 +77813,19 @@ var ts; : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { - if (current !== start && isScope(current)) { - (scopes = scopes || []).push(current); - } - if (current && current.parent && current.parent.kind === 146) { + var scopes = []; + while (true) { + current = current.parent; + if (current.kind === 146) { current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } - else { - current = current.parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 265) { + return scopes; + } } } - return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; @@ -77610,13 +77885,7 @@ var ts; } function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; @@ -78495,6 +78764,67 @@ var ts; })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (context.program.getCompilerOptions().noImplicitAny) { + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, false); + if (ts.isStringLiteral(node) && isModuleIdentifier(node) && ts.getResolvedModule(file, node.text) === undefined) { + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, node.text); + } + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 238: + case 248: + return true; + default: + return false; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; var ruleProvider; @@ -79303,7 +79633,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -79408,15 +79738,16 @@ var ts; } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles()); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, entryName, formattingOptions) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + var ruleProvider = formattingOptions ? getRuleProvider(formattingOptions) : undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles(), host, ruleProvider); } function getCompletionEntrySymbol(fileName, position, entryName) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -79556,11 +79887,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles, isDetailed) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } function getSignatureHelpItems(fileName, position) { synchronizeHostData(); @@ -79742,6 +80073,17 @@ var ts; return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); } + function applyCodeActionCommand(fileName, action) { + fileName = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: fileName, packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -79843,8 +80185,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), + host: host, rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -79897,6 +80240,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -80402,9 +80746,12 @@ var ts; var _this = this; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions); + }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options) { var _this = this; @@ -80673,6 +81020,8 @@ var ts; (function (server) { server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventPackageInstalled = "event::packageInstalled"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; server.EventInitializationFailed = "event::initializationFailed"; @@ -80961,6 +81310,14 @@ var ts; } } server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function indent(string) { + return "\n " + string; + } + server.indent = indent; + function stringifyIndented(json) { + return "\n " + JSON.stringify(json); + } + server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -81038,6 +81395,7 @@ var ts; CommandTypes["BreakpointStatement"] = "breakpointStatement"; CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; CommandTypes["GetCodeFixes"] = "getCodeFixes"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; @@ -81413,14 +81771,14 @@ var ts; var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); ts.mutateMap(missingFileWatches, newMissingFilePathMap, { createNewValue: createMissingFileWatch, - onDeleteValue: ts.closeFileWatcher + onDeleteValue: closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { createNewValue: createWildcardDirectoryWatcher, - onDeleteValue: ts.closeFileWatcherOf, + onDeleteValue: closeFileWatcherOf, onExistingValue: updateWildcardDirectoryWatcher }); function createWildcardDirectoryWatcher(directory, flags) { @@ -81438,8 +81796,6 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; -})(ts || (ts = {})); -(function (ts) { function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -81693,6 +82049,24 @@ var ts; function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, dirPath.charCodeAt(0) === 47 ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; @@ -81704,7 +82078,7 @@ var ts; dirPath = ts.getDirectoryPath(dirPath); } if (isNodeModulesDirectory(dirPath)) { - return { dir: dir, dirPath: dirPath }; + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { @@ -81716,7 +82090,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return { dir: dir, dirPath: dirPath }; + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -81746,13 +82120,15 @@ var ts; var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } - var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath; - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; - } - else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + } } } } @@ -81776,9 +82152,11 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); } } - var dirPath = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath).dirPath; - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - dirWatcher.refCount--; + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + dirWatcher.refCount--; + } } } function createDirectoryWatcher(directory, dirPath) { @@ -81880,7 +82258,7 @@ var ts; closeTypeRootsWatch(); return; } - var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: ts.returnTrue, getCurrentDirectory: getCurrentDirectory }); + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); if (typeRoots) { ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { createNewValue: createTypeRootsWatch, @@ -81891,6 +82269,11 @@ var ts; closeTypeRootsWatch(); } } + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); @@ -81899,6 +82282,8 @@ var ts; var server; (function (server) { server.nullTypingsInstaller = { + isKnownTypesPackageName: ts.returnFalse, + installPackage: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -81957,6 +82342,12 @@ var ts; this.installer = installer; this.perProjectCache = ts.createMap(); } + TypingsCache.prototype.isKnownTypesPackageName = function (name) { + return this.installer.isKnownTypesPackageName(name); + }; + TypingsCache.prototype.installPackage = function (options) { + return this.installer.installPackage(options); + }; TypingsCache.prototype.getTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -82143,6 +82534,19 @@ var ts; } return result.module; }; + Project.prototype.isKnownTypesPackageName = function (name) { + return this.typingsCache.isKnownTypesPackageName(name); + }; + Project.prototype.installPackage = function (options) { + return this.typingsCache.installPackage(__assign({}, options, { projectRootPath: this.toPath(this.currentDirectory) })); + }; + Object.defineProperty(Project.prototype, "typingsCache", { + get: function () { + return this.projectService.typingsCache; + }, + enumerable: true, + configurable: true + }); Project.prototype.getCompilationSettings = function () { return this.compilerOptions; }; @@ -82274,29 +82678,27 @@ var ts; if (!this.builder) { this.builder = ts.createBuilder({ getCanonicalFileName: this.projectService.toCanonicalFileName, - getEmitOutput: function (_program, sourceFile, emitOnlyDts, isDetailed) { - return _this.getFileEmitOutput(sourceFile, emitOnlyDts, isDetailed); - }, - computeHash: function (data) { - return _this.projectService.host.createHash(data); - }, - shouldEmitFile: function (sourceFile) { - return !_this.projectService.getScriptInfoForPath(sourceFile.path).isDynamicOrHasMixedContent(); - } + computeHash: function (data) { return _this.projectService.host.createHash(data); } }); } }; + Project.prototype.shouldEmitFile = function (scriptInfo) { + return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); + }; Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + var _this = this; if (!this.languageServiceEnabled) { return []; } this.updateGraph(); this.ensureBuilder(); - return this.builder.getFilesAffectedBy(this.program, scriptInfo.path); + return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; Project.prototype.emitFile = function (scriptInfo, writeFile) { - this.ensureBuilder(); - var _a = this.builder.emitFile(this.program, scriptInfo.path), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { + return false; + } + var _a = this.getLanguageService(false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; if (!emitSkipped) { for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { var outputFile = outputFiles_1[_i]; @@ -82397,12 +82799,6 @@ var ts; return scriptInfo; }); }; - Project.prototype.getFileEmitOutput = function (sourceFile, emitOnlyDtsFiles, isDetailed) { - if (!this.languageServiceEnabled) { - return undefined; - } - return this.getLanguageService(false).getEmitOutput(sourceFile.fileName, emitOnlyDtsFiles, isDetailed); - }; Project.prototype.getExcludedFiles = function () { return server.emptyArray; }; @@ -82641,14 +83037,14 @@ var ts; return this.missingFilesMap && this.missingFilesMap.has(path); }; Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, undefined, undefined, this.directoryStructureHost); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(fileName); if (scriptInfo && !scriptInfo.isAttached(this)) { return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); } return scriptInfo; }; Project.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + return this.projectService.getScriptInfo(uncheckedFileName); }; Project.prototype.filesToString = function (writeProjectFileNames) { if (!this.program) { @@ -82657,8 +83053,8 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_10 = sourceFiles; _i < sourceFiles_10.length; _i++) { - var file = sourceFiles_10[_i]; + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var file = sourceFiles_9[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -82817,7 +83213,7 @@ var ts; var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.plugins = []; - _this.openRefCount = 0; + _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); _this.enablePlugins(); return _this; @@ -82968,15 +83364,25 @@ var ts; this.configFileSpecs = undefined; _super.prototype.close.call(this); }; - ConfiguredProject.prototype.addOpenRef = function () { - this.openRefCount++; + ConfiguredProject.prototype.addExternalProjectReference = function () { + this.externalProjectRefCount++; }; - ConfiguredProject.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; + ConfiguredProject.prototype.deleteExternalProjectReference = function () { + this.externalProjectRefCount--; }; ConfiguredProject.prototype.hasOpenRef = function () { - return !!this.openRefCount; + var _this = this; + if (!!this.externalProjectRefCount) { + return true; + } + if (this.isClosed()) { + return false; + } + var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + if (this.projectService.hasPendingProjectUpdate(this)) { + return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; + } + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; @@ -83131,7 +83537,22 @@ var ts; server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, - getScriptKind: function (_) { return undefined; }, + getScriptKind: function (fileName, extraFileExtensions) { + var result; + if (extraFileExtensions) { + var fileExtension_1 = ts.getAnyExtensionFromPath(fileName); + if (fileExtension_1) { + ts.some(extraFileExtensions, function (info) { + if (info.extension === fileExtension_1) { + result = info.scriptKind; + return true; + } + return false; + }); + } + } + return result; + }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, }; var externalFilePropertyReader = { @@ -83318,6 +83739,9 @@ var ts; } }); }; + ProjectService.prototype.hasPendingProjectUpdate = function (project) { + return this.pendingProjectUpdates.has(project.getProjectName()); + }; ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { if (!this.eventHandler) { return; @@ -83493,8 +83917,11 @@ var ts; } }, flags, "Wild card directory", project); }; + ProjectService.prototype.getConfigFileExistenceInfo = function (project) { + return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + }; ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (eventKind === ts.FileWatcherEventKind.Deleted) { configFileExistenceInfo.exists = false; this.removeProject(project); @@ -83557,16 +83984,6 @@ var ts; } return project; }; - ProjectService.prototype.addToListOfOpenFiles = function (info) { - ts.Debug.assert(!info.isOrphan()); - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - if (p.projectKind === server.ProjectKind.Configured) { - (p).addOpenRef(); - } - } - this.openFiles.push(info); - }; ProjectService.prototype.closeOpenFile = function (info) { info.close(); this.stopWatchingConfigFilesForClosedScriptInfo(info); @@ -83579,7 +83996,6 @@ var ts; if (info.hasMixedContent) { info.registerFileUpdate(); } - p.deleteOpenRef(); } else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { if (p.isProjectWithSingleRoot()) { @@ -83639,7 +84055,7 @@ var ts; return exists; }; ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (configFileExistenceInfo) { ts.Debug.assert(configFileExistenceInfo.exists); if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { @@ -83660,7 +84076,7 @@ var ts; return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject, __key) { return isRootOfInferredProject; }); }; ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(closedProject.canonicalConfigFilePath); + var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); ts.Debug.assert(!!configFileExistenceInfo); if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { var configFileName = closedProject.getConfigFilePath(); @@ -83848,10 +84264,10 @@ var ts; var projectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw["extends"] !== undefined, - configHasFilesProperty: parsedCommandLine.raw["files"] !== undefined, - configHasIncludeProperty: parsedCommandLine.raw["include"] !== undefined, - configHasExcludeProperty: parsedCommandLine.raw["exclude"] !== undefined, + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, compileOnSave: parsedCommandLine.compileOnSave @@ -83975,7 +84391,7 @@ var ts; scriptInfo = normalizedPath; } else { - var scriptKind = propertyReader.getScriptKind(f); + var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, scriptKind, hasMixedContent, project.directoryStructureHost); path = scriptInfo.path; @@ -84272,7 +84688,8 @@ var ts; sendConfigFileDiagEvent = false; this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } - this.addToListOfOpenFiles(info); + ts.Debug.assert(!info.isOrphan()); + this.openFiles.push(info); if (sendConfigFileDiagEvent) { configFileErrors = project.getAllProjectErrors(); this.sendConfigFileDiagEvent(project, fileName); @@ -84350,11 +84767,14 @@ var ts; this.changedFiles.push(scriptInfo); } }; - ProjectService.prototype.closeConfiguredProject = function (configFile) { + ProjectService.prototype.closeConfiguredProjectReferencedFromExternalProject = function (configFile) { var configuredProject = this.findConfiguredProjectByProjectName(configFile); - if (configuredProject && configuredProject.deleteOpenRef() === 0) { - this.removeProject(configuredProject); - return true; + if (configuredProject) { + configuredProject.deleteExternalProjectReference(); + if (!configuredProject.hasOpenRef()) { + this.removeProject(configuredProject); + return true; + } } return false; }; @@ -84366,7 +84786,7 @@ var ts; var shouldRefreshInferredProjects = false; for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { var configFile = configFiles_1[_i]; - if (this.closeConfiguredProject(configFile)) { + if (this.closeConfiguredProjectReferencedFromExternalProject(configFile)) { shouldRefreshInferredProjects = true; } } @@ -84542,7 +84962,7 @@ var ts; var newConfig = tsConfigFiles[iNew]; var oldConfig = oldConfigFiles[iOld]; if (oldConfig < newConfig) { - this.closeConfiguredProject(oldConfig); + this.closeConfiguredProjectReferencedFromExternalProject(oldConfig); iOld++; } else if (oldConfig > newConfig) { @@ -84555,7 +84975,7 @@ var ts; } } for (var i = iOld; i < oldConfigFiles.length; i++) { - this.closeConfiguredProject(oldConfigFiles[i]); + this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); } } } @@ -84568,7 +84988,7 @@ var ts; project = this.createConfiguredProject(tsconfigFile); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { - project.addOpenRef(); + project.addExternalProjectReference(); } } } @@ -84665,7 +85085,7 @@ var ts; var verboseLogging = logger.hasLevel(server.LogLevel.verbose); var json = JSON.stringify(msg); if (verboseLogging) { - logger.info(msg.type + ": " + json); + logger.info(msg.type + ":" + server.indent(json)); } var len = byteLength(json, "utf8"); return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; @@ -84917,7 +85337,7 @@ var ts; }, _a[server.CommandNames.Configure] = function (request) { _this.projectService.setHostConfiguration(request.arguments); - _this.output(undefined, server.CommandNames.Configure, request.seq); + _this.doOutput(undefined, server.CommandNames.Configure, request.seq, true); return _this.notRequired(); }, _a[server.CommandNames.Reload] = function (request) { @@ -84984,6 +85404,10 @@ var ts; _a[server.CommandNames.GetCodeFixesFull] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); }, + _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { + _this.applyCodeActionCommand(request.command, request.seq, request.arguments); + return _this.notRequired(); + }, _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, @@ -85090,9 +85514,9 @@ var ts; Session.prototype.logError = function (err, cmd) { var msg = "Exception on executing command " + cmd; if (err.message) { - msg += ":\n" + err.message; + msg += ":\n" + server.indent(err.message); if (err.stack) { - msg += "\n" + err.stack; + msg += "\n" + server.indent(err.stack); } } this.logger.msg(msg, server.Msg.Err); @@ -85116,19 +85540,24 @@ var ts; this.send(ev); }; Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { - if (reqSeq === void 0) { reqSeq = 0; } + this.doOutput(info, cmdName, reqSeq, !errorMsg, errorMsg); + }; + Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { var res = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, - success: !errorMsg, + success: success, }; - if (!errorMsg) { + if (success) { res.body = info; } else { - res.message = errorMsg; + ts.Debug.assert(info === undefined); + } + if (message) { + res.message = message; } this.send(res); }; @@ -85750,9 +86179,9 @@ var ts; if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction; var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined }; } }).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } @@ -85761,10 +86190,20 @@ var ts; } }; Session.prototype.getCompletionEntryDetails = function (args) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var position = this.getPositionInFile(args, file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var formattingOptions = project.projectService.getFormatCodeOptions(file); return ts.mapDefined(args.entryNames, function (entryName) { - return project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName, formattingOptions); + if (details) { + var mappedCodeActions = ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action, scriptInfo); }); + return __assign({}, details, { codeActions: mappedCodeActions }); + } + else { + return undefined; + } }); }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { @@ -85856,7 +86295,7 @@ var ts; var project = this.projectService.getDefaultProjectForFile(file, true); this.changeSeq++; if (project.reloadScript(file, tempFileName)) { - this.output(undefined, server.CommandNames.Reload, reqSeq); + this.doOutput(undefined, server.CommandNames.Reload, reqSeq, true); } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { @@ -86058,6 +86497,16 @@ var ts; return codeActions; } }; + Session.prototype.applyCodeActionCommand = function (commandName, requestSeq, args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var output = function (success, message) { return _this.doOutput({}, commandName, requestSeq, success, message); }; + var command = args.command; + project.getLanguageService().applyCodeActionCommand(file, command).then(function (_a) { + var successMessage = _a.successMessage; + output(true, successMessage); + }, function (error) { output(false, error); }); + }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { var startPosition = undefined, endPosition = undefined; if (args.startPosition !== undefined) { @@ -86076,15 +86525,14 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + Session.prototype.mapCodeAction = function (_a, 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); }) - }); }) - }; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands; + var changes = unmappedChanges.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }); + return { description: description, changes: changes, commands: commands }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -86195,8 +86643,8 @@ var ts; return this.executeWithRequestId(request.seq, function () { return handler(request); }); } else { - this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); - this.output(undefined, server.CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); + this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err); + this.doOutput(undefined, server.CommandNames.Unknown, request.seq, false, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; @@ -86206,7 +86654,7 @@ var ts; if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("request: " + message); + this.logger.info("request:" + server.indent(message)); } } var request; @@ -86223,19 +86671,19 @@ var ts; } } if (response) { - this.output(response, request.command, request.seq); + this.doOutput(response, request.command, request.seq, true); } else if (responseRequired) { - this.output(undefined, request.command, request.seq, "No content available."); + this.doOutput(undefined, request.command, request.seq, false, "No content available."); } } catch (err) { if (err instanceof ts.OperationCanceledException) { - this.output({ canceled: true }, request.command, request.seq); + this.doOutput({ canceled: true }, request.command, request.seq, true); return; } this.logError(err, message); - this.output(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); + this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); } }; return Session; @@ -87124,6 +87572,27 @@ var ts; }); } } + NodeTypingsInstaller.prototype.isKnownTypesPackageName = function (name) { + var validationResult = ts.JsTyping.validatePackageName(name); + if (validationResult !== 0) { + return false; + } + if (this.requestedRegistry) { + return !!this.typesRegistryCache && this.typesRegistryCache.has(name); + } + this.requestedRegistry = true; + this.send({ kind: "typesRegistry" }); + return false; + }; + NodeTypingsInstaller.prototype.installPackage = function (options) { + var _this = this; + var rq = __assign({ kind: "installPackage" }, options); + this.send(rq); + ts.Debug.assert(this.packageInstalledPromise === undefined); + return new Promise(function (resolve, reject) { + _this.packageInstalledPromise = { resolve: resolve, reject: reject }; + }); + }; NodeTypingsInstaller.prototype.reportInstallerProcessId = function () { if (this.installerPidReported) { return; @@ -87181,22 +87650,25 @@ var ts; }); }; NodeTypingsInstaller.prototype.onProjectClosed = function (p) { - this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); + this.send({ projectName: p.getProjectName(), kind: "closeProject" }); + }; + NodeTypingsInstaller.prototype.send = function (rq) { + this.installer.send(rq); }; 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.logger.info("Scheduling throttled operation:" + server.stringifyIndented(request)); } } var operationId = project.getProjectName(); var operation = function () { if (_this.logger.hasLevel(server.LogLevel.verbose)) { - _this.logger.info("Sending request: " + JSON.stringify(request)); + _this.logger.info("Sending request:" + server.stringifyIndented(request)); } - _this.installer.send(request); + _this.send(request); }; var queuedRequest = { operationId: operationId, operation: operation }; if (this.activeRequestCount < NodeTypingsInstaller.maxActiveRequestCount) { @@ -87212,9 +87684,23 @@ var ts; }; NodeTypingsInstaller.prototype.handleMessage = function (response) { if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Received response: " + JSON.stringify(response)); + this.logger.info("Received response:" + server.stringifyIndented(response)); } switch (response.kind) { + case server.EventTypesRegistry: + this.typesRegistryCache = ts.createMapFromTemplate(response.typesRegistry); + break; + case server.EventPackageInstalled: { + var success = response.success, message = response.message; + if (success) { + this.packageInstalledPromise.resolve({ successMessage: message }); + } + else { + this.packageInstalledPromise.reject(message); + } + this.packageInstalledPromise = undefined; + break; + } case server.EventInitializationFailed: { if (!this.eventSender) { @@ -87399,7 +87885,7 @@ var ts; function createLogger() { var cmdLineLogFileName = server.findArgument("--logFile"); var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity")); - var envLogOptions = parseLoggingEnvironmentString(process.env["TSS_LOG"]); + var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); var logFileName = cmdLineLogFileName ? ts.stripQuotes(cmdLineLogFileName) : envLogOptions.logToFile @@ -87552,7 +88038,7 @@ var ts; try { var args = [ts.combinePaths(__dirname, "watchGuard.js"), path]; if (logger.hasLevel(server.LogLevel.verbose)) { - logger.info("Starting " + process.execPath + " with args " + JSON.stringify(args)); + logger.info("Starting " + process.execPath + " with args:" + server.stringifyIndented(args)); } childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { "ELECTRON_RUN_AS_NODE": "1" } }); status = true; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index e983ac73b1551..ee118279bcb18 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -2158,6 +2158,7 @@ declare namespace ts { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface DiagnosticMessage { key: string; @@ -3207,10 +3208,11 @@ declare namespace ts { }; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @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 @@ -3729,17 +3731,11 @@ declare namespace ts { outputFiles: OutputFile[]; emitSkipped: boolean; } - interface EmitOutputDetailed extends EmitOutput { - diagnostics: Diagnostic[]; - sourceMaps: SourceMapData[]; - emittedSourceFiles: SourceFile[]; - } interface OutputFile { name: string; writeByteOrderMark: boolean; text: string; } - function getFileEmitOutput(program: Program, sourceFile: SourceFile, emitOnlyDtsFiles: boolean, isDetailed: boolean, cancellationToken?: CancellationToken, customTransformers?: CustomTransformers): EmitOutput | EmitOutputDetailed; } declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; @@ -3868,7 +3864,11 @@ declare namespace ts { interface HostCancellationToken { isCancellationRequested(): boolean; } - interface LanguageServiceHost { + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { getCompilationSettings(): CompilerOptions; getNewLine?(): string; getProjectVersion?(): string; @@ -3890,12 +3890,13 @@ declare namespace ts { getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - directoryExists?(directoryName: string): boolean; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. */ getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; } interface LanguageService { cleanupSemanticCache(): void; @@ -3913,7 +3914,7 @@ declare namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, options?: FormatCodeOptions | FormatCodeSettings): CompletionEntryDetails; getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; @@ -3943,13 +3944,16 @@ declare namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, isDetailed?: boolean): EmitOutput | EmitOutputDetailed; getProgram(): Program; dispose(): void; } + interface ApplyCodeActionCommandResult { + successMessage: string; + } interface Classifications { spans: number[]; endOfLineState: EndOfLineState; @@ -4014,6 +4018,14 @@ declare namespace ts { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + type CodeActionCommand = InstallPackageAction; + interface InstallPackageAction { } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. @@ -4062,6 +4074,7 @@ declare namespace ts { edits: FileTextChanges[]; renameFilename: string | undefined; renameLocation: number | undefined; + commands?: CodeActionCommand[]; } interface TextInsertion { newText: string; @@ -4281,6 +4294,7 @@ declare namespace ts { * be used in that case */ replacementSpan?: TextSpan; + hasAction?: true; } interface CompletionEntryDetails { name: string; @@ -4289,6 +4303,7 @@ declare namespace ts { displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; tags: JSDocTagInfo[]; + codeActions?: CodeAction[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -4630,11 +4645,10 @@ declare namespace ts.server { interface SortedReadonlyArray extends ReadonlyArray { " __sortedArrayBrand": any; } - interface TypingInstallerRequest { + interface TypingInstallerRequestWithProjectName { readonly projectName: string; - readonly kind: "discover" | "closeProject"; } - interface DiscoverTypings extends TypingInstallerRequest { + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { readonly fileNames: string[]; readonly projectRootPath: Path; readonly compilerOptions: CompilerOptions; @@ -4643,16 +4657,27 @@ declare namespace ts.server { readonly cachePath?: string; readonly kind: "discover"; } - interface CloseProject extends TypingInstallerRequest { + interface CloseProject extends TypingInstallerRequestWithProjectName { readonly kind: "closeProject"; } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; + type EventTypesRegistry = "event::typesRegistry"; + type EventPackageInstalled = "event::packageInstalled"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | EventPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; @@ -4688,6 +4713,8 @@ declare namespace ts.server { declare namespace ts.server { const ActionSet: ActionSet; const ActionInvalidate: ActionInvalidate; + const EventTypesRegistry: EventTypesRegistry; + const EventPackageInstalled: EventPackageInstalled; const EventBeginInstallTypes: EventBeginInstallTypes; const EventEndInstallTypes: EventEndInstallTypes; const EventInitializationFailed: EventInitializationFailed; @@ -4825,6 +4852,7 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", @@ -4846,6 +4874,7 @@ declare namespace ts.server.protocol { * Client-initiated request message */ interface Request extends Message { + type: "request"; /** * The command to execute */ @@ -4865,6 +4894,7 @@ declare namespace ts.server.protocol { * Server-initiated event message */ interface Event extends Message { + type: "event"; /** * Name of event */ @@ -4878,6 +4908,7 @@ declare namespace ts.server.protocol { * Response by server to client request message. */ interface Response extends Message { + type: "response"; /** * Sequence number of the request message. */ @@ -4891,7 +4922,8 @@ declare namespace ts.server.protocol { */ command: string; /** - * Contains error message if success === false. + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. */ message?: string; /** @@ -5167,6 +5199,12 @@ declare namespace ts.server.protocol { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } interface FileRangeRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). @@ -5194,6 +5232,9 @@ declare namespace ts.server.protocol { */ errorCodes?: number[]; } + interface ApplyCodeActionCommandRequestArgs extends FileRequestArgs { + command: {}; + } /** * Response for GetCodeFixes request. */ @@ -5932,6 +5973,8 @@ declare namespace ts.server.protocol { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; } /** * Format and format on key response message. @@ -6038,6 +6081,11 @@ declare namespace ts.server.protocol { * this span should be used instead of the default one. */ replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; } /** * Additional completion entry details, available on demand @@ -6067,6 +6115,10 @@ declare namespace ts.server.protocol { * JSDoc tags for the symbol. */ tags: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; } interface CompletionsResponse extends Response { body?: CompletionEntry[]; @@ -6840,6 +6892,7 @@ declare namespace ts.server { send(msg: protocol.Message): void; event(info: T, eventName: string): void; output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; + private doOutput(info, cmdName, reqSeq, success, message?); private semanticCheck(file, project); private syntacticCheck(file, project); private updateErrorCheck(next, checkList, ms, requireOpen?); @@ -6915,8 +6968,9 @@ declare namespace ts.server { private getApplicableRefactors(args); private getEditsForRefactor(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); + private applyCodeActionCommand(commandName, requestSeq, args); private getStartAndEndPosition(args, scriptInfo); - private mapCodeAction(codeAction, scriptInfo); + private mapCodeAction({description, changes: unmappedChanges, commands}, scriptInfo); private mapTextChangesToCodeEdits(project, textChanges); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); @@ -6926,19 +6980,17 @@ declare namespace ts.server { private notRequired(); private requiredResponse(response); private handlers; - addProtocolHandler(command: string, handler: (request: protocol.Request) => { - response?: any; - responseRequired: boolean; - }): void; + addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; private setCurrentRequest(requestId); private resetCurrentRequest(requestId); executeWithRequestId(requestId: number, f: () => T): T; - executeCommand(request: protocol.Request): { - response?: any; - responseRequired?: boolean; - }; + executeCommand(request: protocol.Request): HandlerResponse; onMessage(message: string): void; } + interface HandlerResponse { + response?: {}; + responseRequired?: boolean; + } } declare namespace ts.server { class ScriptInfo { @@ -6985,25 +7037,13 @@ declare namespace ts.server { isJavaScript(): boolean; } } -declare namespace ts { - /** - * Updates the existing missing file watches with the new set of missing files after new program is created - */ - function updateMissingFilePathsWatch(program: Program, missingFileWatches: Map, createMissingFileWatch: (missingFilePath: Path) => FileWatcher): void; - interface WildcardDirectoryWatcher { - watcher: FileWatcher; - flags: WatchDirectoryFlags; - } - /** - * Updates the existing wild card directory watches with the new set of wild card directories from the config file - * after new program is created because the config file was reloaded or program was created first time from the config file - * Note that there is no need to call this function when the program is updated with additional files without reloading config files, - * as wildcard directories wont change unless reloading config file - */ - function updateWatchingWildcardDirectories(existingWatchedForWildcards: Map, wildcardDirectories: Map, watchDirectory: (directory: string, flags: WatchDirectoryFlags) => FileWatcher): void; -} declare namespace ts.server { + interface InstallPackageOptionsWithProjectRootPath extends InstallPackageOptions { + projectRootPath: Path; + } interface ITypingsInstaller { + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptionsWithProjectRootPath): Promise; enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray): void; attach(projectService: ProjectService): void; onProjectClosed(p: Project): void; @@ -7014,6 +7054,8 @@ declare namespace ts.server { private readonly installer; private readonly perProjectCache; constructor(installer: ITypingsInstaller); + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptionsWithProjectRootPath): Promise; getTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray, forceRefresh: boolean): SortedReadonlyArray; updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]): void; deleteTypingsForProject(projectName: string): void; @@ -7108,6 +7150,9 @@ declare namespace ts.server { isJsOnlyProject(): boolean; getCachedUnresolvedImportsPerFile_TestOnly(): UnresolvedImportsMap; static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {}; + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptions): Promise; + private readonly typingsCache; getCompilationSettings(): CompilerOptions; getCompilerOptions(): CompilerOptions; getNewLine(): string; @@ -7136,6 +7181,7 @@ declare namespace ts.server { getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; private ensureBuilder(); + private shouldEmitFile(scriptInfo); getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; /** * Returns true if emit was conducted @@ -7154,7 +7200,6 @@ declare namespace ts.server { getRootFiles(): NormalizedPath[]; getRootScriptInfos(): ScriptInfo[]; getScriptInfos(): ScriptInfo[]; - private getFileEmitOutput(sourceFile, emitOnlyDtsFiles, isDetailed); getExcludedFiles(): ReadonlyArray; getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): NormalizedPath[]; hasConfigFile(configFilePath: NormalizedPath): boolean; @@ -7212,8 +7257,8 @@ declare namespace ts.server { private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; private plugins; - /** Used for configured projects which may have multiple open roots */ - openRefCount: number; + /** Ref count to the project when opened from external project */ + private externalProjectRefCount; private projectErrors; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph @@ -7237,9 +7282,6 @@ declare namespace ts.server { getTypeAcquisition(): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; close(): void; - addOpenRef(): void; - deleteOpenRef(): number; - hasOpenRef(): boolean; getEffectiveTypeRoots(): string[]; } /** @@ -7469,7 +7511,6 @@ declare namespace ts.server { */ private onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); private removeProject(project); - private addToListOfOpenFiles(info); /** * Remove this file from the set of open, non-configured files. * @param info The file that has been closed or newly configured @@ -7577,7 +7618,7 @@ declare namespace ts.server { */ closeClientFile(uncheckedFileName: string): void; private collectChanges(lastKnownProjectVersions, currentProjects, result); - private closeConfiguredProject(configFile); + private closeConfiguredProjectReferencedFromExternalProject(configFile); closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; openExternalProjects(projects: protocol.ExternalProject[]): void; /** Makes a filename safe to insert in a RegExp */ diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 4454ca3c8a487..9171f58b35539 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1386,8 +1386,8 @@ var ts; // Using 'delete' on an object causes V8 to put the object in dictionary mode. // This disables creation of hidden classes, which are expensive when an object is // constantly changing shape. - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } /** Create a new map. If a template object is provided, the map will copy entries from it. */ @@ -1527,6 +1527,17 @@ var ts; return undefined; } ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1585,6 +1596,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { @@ -2415,6 +2436,15 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -3785,6 +3815,16 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3936,8 +3976,13 @@ var ts; if (parentResult) { var baseName = getBaseNameOfFileName(fileOrDirectory); if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, baseName, host.fileExists(fileOrDirectoryPath)); - updateFileSystemEntry(parentResult.directories, baseName, host.directoryExists(fileOrDirectoryPath)); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + updateFileSystemEntry(parentResult.directories, baseName, fsQueryResult.directoryExists); + return fsQueryResult; } } } @@ -4002,7 +4047,7 @@ var ts; var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); // One file can have multiple watchers @@ -4401,7 +4446,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -5362,9 +5407,9 @@ var ts; Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), 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: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "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: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\"."), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\"."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), @@ -5871,6 +5916,17 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + /* @internal */ + function isAnyImportSyntax(node) { + switch (node.kind) { + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -6677,6 +6733,14 @@ var ts; return node && !!(node.flags & 1048576 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). @@ -6701,6 +6765,10 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(string, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, string).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; /** * Returns true if the node is a variable declaration whose initializer is a function expression. * This function does not test if the node is in a JavaScript file or not. @@ -18747,8 +18815,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -18885,8 +18953,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -20209,7 +20277,7 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 /* StringLiteral */ && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34 /* doubleQuote */; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { @@ -20448,9 +20516,9 @@ var ts; }; function getFileNames() { var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - filesSpecs = raw["files"]; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } @@ -20460,25 +20528,25 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } @@ -20558,7 +20626,7 @@ var ts; var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, 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 typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { @@ -20676,7 +20744,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -21986,6 +22054,7 @@ var ts; loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); } + /* @internal */ function getPackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { @@ -21993,6 +22062,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); } @@ -22039,18 +22109,26 @@ var ts; /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); // Take off the "@" - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" } } - return moduleName; + return packageName; } /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { @@ -25759,6 +25837,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -31903,13 +31982,11 @@ var ts; function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -32764,7 +32841,7 @@ var ts; } var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; + spread.flags |= 1048576 /* FreshLiteral */ | 4194304 /* ContainsObjectLiteral */; spread.objectFlags |= 128 /* ObjectLiteral */; spread.symbol = symbol; return spread; @@ -35944,6 +36021,16 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { + if (type.flags & 524288 /* IndexedAccess */) { + // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to + // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -39277,7 +39364,7 @@ var ts; return unknownType; } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); + markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -39454,12 +39541,19 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -43007,7 +43101,10 @@ var ts; // There is no resolved symbol cached if the type resolved to a builtin // via JSDoc type reference resolution (eg, Boolean became boolean), none // of which are generic when they have no associated symbol - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + // (additionally, JSDoc's index signature syntax, Object actually uses generic syntax without being generic) + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; @@ -44378,7 +44475,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined); // A destructuring is never a write-only reference. + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -48752,13 +48849,16 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -72851,44 +72951,30 @@ var ts; })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); /// +/* @internal */ var ts; (function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; - var emittedSourceFiles; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - if (!isDetailed) { - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - } - return { - outputFiles: outputFiles, - emitSkipped: emitResult.emitSkipped, - diagnostics: emitResult.diagnostics, - sourceMaps: emitResult.sourceMaps, - emittedSourceFiles: emittedSourceFiles - }; - function writeFile(fileName, text, writeByteOrderMark, _onError, sourceFiles) { + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - if (isDetailed) { - emittedSourceFiles = ts.addRange(emittedSourceFiles, sourceFiles); - } } } ts.getFileEmitOutput = getFileEmitOutput; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { function createBuilder(options) { var isModuleEmit; var fileInfos = ts.createMap(); var semanticDiagnosticsPerFile = ts.createMap(); /** The map has key by source file's path that has been changed */ - var changedFileNames = ts.createMap(); + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; var emitHandler; return { updateProgram: updateProgram, getFilesAffectedBy: getFilesAffectedBy, - emitFile: emitFile, emitChangedFiles: emitChangedFiles, getSemanticDiagnostics: getSemanticDiagnostics, clear: clear @@ -72901,6 +72987,8 @@ var ts; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { // Add new file info createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, @@ -72910,28 +72998,31 @@ var ts; onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } }); } - function registerChangedFile(path, fileName) { - changedFileNames.set(path, fileName); + function registerChangedFile(path) { + changedFilesSet.set(path, true); // All changed files need to re-evaluate its semantic diagnostics semanticDiagnosticsPerFile.delete(path); } function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); emitHandler.onAddSourceFile(program, sourceFile); - return { fileName: sourceFile.fileName, version: sourceFile.version, signature: undefined }; + return { version: sourceFile.version, signature: undefined }; } - function removeExistingFileInfo(existingFileInfo, path) { - registerChangedFile(path, existingFileInfo.fileName); + function removeExistingFileInfo(_existingFileInfo, path) { + // Since we dont need to track removed file as changed file + // We can just remove its diagnostics + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); emitHandler.onRemoveSourceFile(path); } function updateExistingFileInfo(program, existingInfo, sourceFile) { if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); } } function ensureProgramGraph(program) { @@ -72946,93 +73037,80 @@ var ts; } function getFilesAffectedBy(program, path) { ensureProgramGraph(program); - var sourceFile = program.getSourceFile(path); - var singleFileResult = sourceFile && options.shouldEmitFile(sourceFile) ? [sourceFile.fileName] : []; - var info = fileInfos.get(path); - if (!info || !updateShapeSignature(program, sourceFile, info)) { - return singleFileResult; + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; } - ts.Debug.assert(!!sourceFile); - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult); + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); } - function emitFile(program, path) { + function emitChangedFiles(program, writeFileCallback) { ensureProgramGraph(program); - if (!fileInfos.has(path)) { - return { outputFiles: [], emitSkipped: true }; + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + // With --out or --outFile all outputs go into single file, do it only once + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; } - return options.getEmitOutput(program, program.getSourceFileByPath(path), /*emitOnlyDtsFiles*/ false, /*isDetailed*/ false); - } - function enumerateChangedFilesSet(program, onChangedFile, onAffectedFile) { - changedFileNames.forEach(function (fileName, path) { - onChangedFile(fileName, path); - var affectedFiles = getFilesAffectedBy(program, path); - for (var _i = 0, affectedFiles_1 = affectedFiles; _i < affectedFiles_1.length; _i++) { - var file = affectedFiles_1[_i]; - onAffectedFile(file, program.getSourceFile(file)); - } - }); - } - function enumerateChangedFilesEmitOutput(program, emitOnlyDtsFiles, onChangedFile, onEmitOutput) { var seenFiles = ts.createMap(); - enumerateChangedFilesSet(program, onChangedFile, function (fileName, sourceFile) { - if (!seenFiles.has(fileName)) { - seenFiles.set(fileName, true); - if (sourceFile) { - // Any affected file shouldnt have the cached diagnostics - semanticDiagnosticsPerFile.delete(sourceFile.path); - var emitOutput = options.getEmitOutput(program, sourceFile, emitOnlyDtsFiles, /*isDetailed*/ true); - onEmitOutput(emitOutput, sourceFile); - // mark all the emitted source files as seen - if (emitOutput.emittedSourceFiles) { - for (var _i = 0, _a = emitOutput.emittedSourceFiles; _i < _a.length; _i++) { - var file = _a[_i]; - seenFiles.set(file.fileName, true); - } - } + var result; + changedFilesSet.forEach(function (_true, path) { + // Get the affected Files by this program + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + // Affected files shouldnt have cached diagnostics + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + // Emit the affected file + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); } - } + }); }); - } - function emitChangedFiles(program) { - ensureProgramGraph(program); - var result = []; - enumerateChangedFilesEmitOutput(program, /*emitOnlyDtsFiles*/ false, - /*onChangedFile*/ ts.noop, function (emitOutput) { return result.push(emitOutput); }); - changedFileNames.clear(); - return result; + changedFilesSet.clear(); + return result || ts.emptyArray; } function getSemanticDiagnostics(program, cancellationToken) { ensureProgramGraph(program); - // Ensure that changed files have cleared their respective - enumerateChangedFilesSet(program, /*onChangedFile*/ ts.noop, function (_affectedFileName, sourceFile) { - if (sourceFile) { - semanticDiagnosticsPerFile.delete(sourceFile.path); - } - }); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + // We dont need to cache the diagnostics just return them from program + return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } var diagnostics; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - diagnostics = ts.addRange(diagnostics, cachedDiagnostics); - } - else { - // Diagnostics werent cached, get them from program, and cache the result - var cachedDiagnostics_1 = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, cachedDiagnostics_1); - diagnostics = ts.addRange(diagnostics, cachedDiagnostics_1); - } + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); } return diagnostics || ts.emptyArray; } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } function clear() { isModuleEmit = undefined; emitHandler = undefined; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); - changedFileNames.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); } /** * For script files that contains only ambient external modules, although they are not actually external module files, @@ -73052,15 +73130,23 @@ var ts; /** * @return {boolean} indicates if the shape signature has changed since last update. */ - function updateShapeSignature(program, sourceFile, info) { + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { - latestSignature = options.computeHash(sourceFile.text); + latestSignature = sourceFile.version; info.signature = latestSignature; } else { - var emitOutput = options.getEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true, /*isDetailed*/ false); + var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = options.computeHash(emitOutput.outputFiles[0].text); info.signature = latestSignature; @@ -73121,24 +73207,26 @@ var ts; } } /** - * Gets all the emittable files from the program. - * @param firstSourceFile This one will be emitted first. See https://github.com/Microsoft/TypeScript/issues/16888 + * Gets all files of the program excluding the default library file */ - function getAllEmittableFiles(program, firstSourceFile) { - var defaultLibraryFileName = ts.getDefaultLibFileName(program.getCompilerOptions()); - var sourceFiles = program.getSourceFiles(); - var result = []; - add(firstSourceFile); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + // Use cached result + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; if (sourceFile !== firstSourceFile) { - add(sourceFile); + addSourceFile(sourceFile); } } - return result; - function add(sourceFile) { - if (ts.getBaseFileName(sourceFile.fileName) !== defaultLibraryFileName && options.shouldEmitFile(sourceFile)) { - result.push(sourceFile.fileName); + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); } } } @@ -73150,14 +73238,14 @@ var ts; onUpdateSourceFileWithSameVersion: ts.returnFalse, getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape }; - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { var options = program.getCompilerOptions(); // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, // so returning the file itself is good enough. if (options && (options.out || options.outFile)) { - return singleFileResult; + return [sourceFile]; } - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } } function getModuleEmitHandler() { @@ -73207,7 +73295,7 @@ var ts; // add files referencing the removedFilePath, as changed files too var referencedByInfo = fileInfos.get(filePath); if (referencedByInfo) { - registerChangedFile(filePath, referencedByInfo.fileName); + registerChangedFile(filePath); } } }); @@ -73220,33 +73308,30 @@ var ts; return referencesInFile.has(referencedFilePath) ? filePath : undefined; }); } - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } var compilerOptions = program.getCompilerOptions(); if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return singleFileResult; + return [sourceFile]; } // Now we need to if each file in the referencedBy list has a shape change as well. // Because if so, its own referencedBy files need to be saved as well to make the // emitting result consistent with files on disk. var seenFileNamesMap = ts.createMap(); - var setSeenFileName = function (path, sourceFile) { - seenFileNamesMap.set(path, sourceFile && options.shouldEmitFile(sourceFile) ? sourceFile.fileName : undefined); - }; // Start with the paths this file was referenced by var path = sourceFile.path; - setSeenFileName(path, sourceFile); + seenFileNamesMap.set(path, sourceFile); var queue = getReferencedByPaths(path); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = program.getSourceFileByPath(currentPath); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile, fileInfos.get(currentPath))) { + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { queue.push.apply(queue, getReferencedByPaths(currentPath)); } - setSeenFileName(currentPath, currentSourceFile); } } // Return array of values that needs emit @@ -74333,8 +74418,9 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - // For JavaScript files, we don't want to report semantic errors unless explicitly requested. - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || ts.isCheckJsEnabledForFile(sourceFile, options); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -74971,8 +75057,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var file = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var file = sourceFiles_2[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -74983,8 +75069,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -76743,9 +76829,7 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -76766,6 +76850,10 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -78836,18 +78924,18 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, @@ -78875,14 +78963,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -78938,7 +79026,7 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, symbolToOriginInfoMap) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { @@ -78948,6 +79036,9 @@ var ts; if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { + if (symbolToOriginInfoMap && symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, typeChecker)]) { + entry.hasAction = true; + } entries.push(entry); uniqueNames.set(id, true); } @@ -79092,46 +79183,61 @@ var ts; } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, name, allSourceFiles, host, rulesProvider) { // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (completionData) { - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; // 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(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === entryName ? s : undefined; }); + var symbol = ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === name; }); if (symbol) { + var codeActions = getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, rulesProvider); + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions }; } } // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; }); if (keywordCompletion) { return { - name: entryName, + name: name, kind: "keyword" /* keyword */, kindModifiers: "" /* none */, - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, - tags: undefined + tags: undefined, + codeActions: undefined, }; } return undefined; } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + function getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, rulesProvider) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, checker)]; + if (!symbolOriginInfo) { + return undefined; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + return ts.codefix.getCodeActionForImport(moduleSymbol, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + rulesProvider: rulesProvider, + symbolName: symbol.name, + getCanonicalFileName: ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false), + symbolToken: undefined, + kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, + }); + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName, allSourceFiles) { // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } @@ -79140,10 +79246,10 @@ var ts; // 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(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName ? s : undefined; }); + return ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var request; var start = ts.timestamp(); @@ -79208,7 +79314,18 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; + return { + symbols: undefined, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0 /* None */, + symbolToOriginInfoMap: undefined, + }; } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -79299,6 +79416,7 @@ var ts; var isNewIdentifierLocation; var keywordFilters = 0 /* None */; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } @@ -79331,7 +79449,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 279 /* JSDocParameterTag */: @@ -79485,11 +79603,13 @@ var ts; ts.isStatement(scopeNode); } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : ""); + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { @@ -79550,6 +79670,53 @@ var ts; return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var symbolIdMap = ts.arrayToNumericMap(symbols, function (s) { return ts.getUniqueSymbolId(s, typeChecker); }); + ts.codefix.forEachExternalModule(typeChecker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + } + var id = ts.getUniqueSymbolId(symbol, typeChecker); + if (!symbolIdMap[id] && stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[id] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -80244,7 +80411,7 @@ var ts; // First check of the displayName is not external module; if it is an external module, it is not valid entry if (symbol.flags & 1920 /* Namespace */) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; @@ -81284,8 +81451,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 265 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -81315,8 +81482,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -81901,19 +82068,25 @@ var ts; var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + if (node.kind === 79 /* DefaultKeyword */) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; @@ -82221,8 +82394,8 @@ var ts; } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } @@ -82756,8 +82929,8 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); @@ -83894,6 +84067,66 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + 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 = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var MaxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > MaxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + MaxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + throw ts.Debug.fail(); // Shouldn't have called this. + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /* @internal */ @@ -83914,8 +84147,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var sourceFile = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); @@ -89820,22 +90053,22 @@ var ts; * It can be changed to side-table later if we decide that current design is too invasive. */ function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -89932,6 +90165,11 @@ var ts; ChangeTracker.fromContext = function (context) { return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; @@ -90833,6 +91071,42 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_module_0.code, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); // These errors should only happen on the module name. + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + // If !registry, registry not available yet, can't do anything. + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: "Install '" + typesPackageName + "'", + changes: [], + commands: [{ type: "install package", packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -91264,6 +91538,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -91367,483 +91642,470 @@ var ts; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName_2; - if (umdSymbol.flags & 2097152 /* Alias */) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName_2 = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455 /* Value */)); - symbolName_2 = symbol.name; - } - else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + rulesProvider: context.rulesProvider, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbol, context) { + var declarations = getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + var actions = []; + if (context.symbolToken) { + // 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. + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } - return getCodeActionForImport(symbol, symbolName_2, /*isDefault*/ false, /*isNamespaceImport*/ true); } - var candidateModules = 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)) { - candidateModules.push(otherSourceFile.symbol); - } + actions.push(getCodeActionForAddImport(moduleSymbol, context, declarations)); + return actions; + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 240 /* NamespaceImport */ ? namedBindings.name : undefined; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_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.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); - } - } - // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(name !== "default"); - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); - } + else { + return declaration.name; } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + } + // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238 /* ImportDeclaration */: - return parent; - case 248 /* ExternalModuleReference */: - return parent.parent; - default: - return undefined; - } - } } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); - } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238 /* ImportDeclaration */: + return parent; + case 248 /* ExternalModuleReference */: + return parent.parent; + default: + ts.Debug.assert(parent.kind === 244 /* ExportDeclaration */); + // Ignore these, can't add imports to them. + return undefined; } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - 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); + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createImportClauseOfKind(kind, symbolName), createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - return [getCodeActionForNewImport()]; + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - 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_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* 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 (!isNamespaceImport && 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 fileTextChanges = 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], fileTextChanges, "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 === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); - } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); + }); + // 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. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + switch (kind) { + case 1 /* Default */: + return ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined); + case 2 /* Namespace */: + return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))); + case 0 /* Named */: + return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); + default: + ts.Debug.assertNever(kind); + } + } + function getModuleSpecifierForNewImport(sourceFile, moduleSymbol, options, getCanonicalFileName, host) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + return tryGetModuleNameFromAmbientModule(moduleSymbol) || + tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) || + tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) || + tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) || + options.rootDirs && tryGetModuleNameFromRootDirs(options.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName)); + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) { + if (!options.baseUrl) { + return undefined; + } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl, getCanonicalFileName); + if (!relativeName) { + return undefined; + } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + 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; } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); + 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 { - namespacePrefix = declaration.name.getText(); + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; } - 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], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; + } + return relativeName; + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1)); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // 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. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } - }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39 /* singleQuote */; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - 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 || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - 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); - } - } - } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; - } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; } - return undefined; - } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + else { + state = 3 /* PackageContent */; } - return fileName; - } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionForAddImport(moduleSymbol, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 238 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ctx.kind, declaration.importClause); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + }); + if (fromExistingImport) { + return fromExistingImport; + } + var moduleSpecifier = ts.firstDefined(declarations, moduleSpecifierFromAnyImport) + || getModuleSpecifierForNewImport(ctx.sourceFile, moduleSymbol, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return getCodeActionForNewImport(ctx, moduleSpecifier); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 238 /* ImportDeclaration */ + ? node.moduleSpecifier + : node.moduleReference.kind === 248 /* ExternalModuleReference */ + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, kind, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + var name = importClause.name, namedBindings = importClause.namedBindings; + switch (kind) { + case 1 /* Default */: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0 /* Named */: { + var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 241 /* NamedImports */ && namedBindings.elements.length !== 0) { + // There are already named imports; add another. + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 241 /* NamedImports */ && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); + }); } + return undefined; } + case 2 /* Namespace */: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + default: + ts.Debug.assertNever(kind); } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + /** + * 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, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", + /*moduleSpecifier*/ undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbolName = symbol.name; + } + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: 2 /* Namespace */ })); } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.escapedName === symbolName && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = ts.getUniqueSymbolId(localSymbol, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); + } + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol); + } + } + } + codefix.forEachExternalModule = forEachExternalModule; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92581,7 +92843,7 @@ var ts; if (!usageContext.properties) { usageContext.properties = ts.createUnderscoreEscapedMap(); } - var propertyUsageContext = {}; + var propertyUsageContext = usageContext.properties.get(name) || {}; inferTypeFromContext(parent, checker, propertyUsageContext); usageContext.properties.set(name, propertyUsageContext); } @@ -92632,7 +92894,7 @@ var ts; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); members_4.set(name, symbol); }); } @@ -92688,7 +92950,7 @@ var ts; symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); parameters.push(symbol); } - var returnType = getTypeFromUsageContext(callContext.returnType, checker); + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { @@ -92707,6 +92969,7 @@ var ts; /// /// /// +/// /// /// /// @@ -92722,55 +92985,66 @@ var ts; var ts; (function (ts) { var refactor; - (function (refactor_2) { + (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { var actionName = "annotate"; var annotateTypeFromJSDoc = { name: "Annotate with type from JSDoc", description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAnnotation, - getAvailableActions: getAvailableActions - }; - var annotateFunctionFromJSDoc = { - name: "Annotate with types from JSDoc", - description: ts.Diagnostics.Annotate_with_types_from_JSDoc.message, - getEditsForAction: getEditsForFunctionAnnotation, + getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }; - refactor_2.registerRefactor(annotateTypeFromJSDoc); - refactor_2.registerRefactor(annotateFunctionFromJSDoc); + refactor.registerRefactor(annotateTypeFromJSDoc); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; } var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); - var decl = ts.findAncestor(node, isDeclarationWithType); - if (!decl || decl.type) { - return undefined; - } - var jsdocType = ts.getJSDocType(decl); - var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); - var refactor = (isFunctionWithJSDoc || jsdocType && decl.kind === 146 /* Parameter */) ? annotateFunctionFromJSDoc : - jsdocType ? annotateTypeFromJSDoc : - undefined; - if (refactor) { + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: refactor.name, - description: refactor.description, + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, actions: [ { - description: refactor.description, + description: annotateTypeFromJSDoc.description, name: actionName } ] }]; } } - function getEditsForAnnotation(context, action) { + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { if (actionName !== action) { return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 146 /* Parameter */) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); var decl = ts.findAncestor(token, isDeclarationWithType); @@ -92788,10 +93062,7 @@ var ts; renameLocation: undefined }; } - function getEditsForFunctionAnnotation(context, action) { - if (actionName !== action) { - return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); - } + function getEditsForFunctionAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); @@ -92870,7 +93141,9 @@ var ts; case 159 /* TypeReference */: return transformJSDocTypeReference(node); default: - return ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; } } function transformJSDocOptionalType(node) { @@ -92897,6 +93170,9 @@ var ts; var name = node.typeName; var args = node.typeArguments; if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } var text = node.typeName.text; switch (node.typeName.text) { case "String": @@ -92921,7 +93197,18 @@ var ts; } return ts.createTypeReferenceNode(name, args); } - })(annotateWithTypeFromJSDoc = refactor_2.annotateWithTypeFromJSDoc || (refactor_2.annotateWithTypeFromJSDoc = {})); + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -93587,27 +93874,26 @@ var ts; : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 146 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. // Walk up to the closest parent of a place where we can logically put a sibling: // * Function declaration // * Class declaration or expression // * Module/namespace or source file - if (current !== start && isScope(current)) { - (scopes = scopes || []).push(current); - } - // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current && current.parent && current.parent.kind === 146 /* Parameter */) { - // Skip all the way to the outer scope of the function that declared this parameter - current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; - } - else { - current = current.parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 265 /* SourceFile */) { + return scopes; + } } } - return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; @@ -93674,13 +93960,7 @@ var ts; } function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; @@ -94717,9 +94997,73 @@ var ts; })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (context.program.getCompilerOptions().noImplicitAny) { + // Then it will be available via `fixCannotFindModule`. + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); // Should be defined if we said there was an action available. + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + if (ts.isStringLiteral(node) && isModuleIdentifier(node) && ts.getResolvedModule(file, node.text) === undefined) { + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, node.text); + } + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 238 /* ImportDeclaration */: + case 248 /* ExternalModuleReference */: + return true; + default: + return false; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /// +/// /// /// /// @@ -95620,7 +95964,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -95773,15 +96117,16 @@ var ts; } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles()); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, entryName, formattingOptions) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + var ruleProvider = formattingOptions ? getRuleProvider(formattingOptions) : undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles(), host, ruleProvider); } function getCompletionEntrySymbol(fileName, position, entryName) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -95930,11 +96275,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles, isDetailed) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } // Signature help /** @@ -96138,6 +96483,17 @@ var ts; return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); } + function applyCodeActionCommand(fileName, action) { + fileName = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: fileName, packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -96312,8 +96668,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), + host: host, rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -96366,6 +96723,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -96506,6 +96864,8 @@ var ts; (function (server) { server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventPackageInstalled = "event::packageInstalled"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; server.EventInitializationFailed = "event::initializationFailed"; @@ -96812,6 +97172,17 @@ var ts; } } server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + /* @internal */ + function indent(string) { + return "\n " + string; + } + server.indent = indent; + /** Put stringified JSON on the next line, indented. */ + /* @internal */ + function stringifyIndented(json) { + return "\n " + JSON.stringify(json); + } + server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); /** @@ -96916,6 +97287,7 @@ var ts; CommandTypes["BreakpointStatement"] = "breakpointStatement"; CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; CommandTypes["GetCodeFixes"] = "getCodeFixes"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; /* @internal */ CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; @@ -97066,7 +97438,7 @@ var ts; var verboseLogging = logger.hasLevel(server.LogLevel.verbose); var json = JSON.stringify(msg); if (verboseLogging) { - logger.info(msg.type + ": " + json); + logger.info(msg.type + ":" + server.indent(json)); } var len = byteLength(json, "utf8"); return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; @@ -97327,7 +97699,7 @@ var ts; }, _a[server.CommandNames.Configure] = function (request) { _this.projectService.setHostConfiguration(request.arguments); - _this.output(undefined, server.CommandNames.Configure, request.seq); + _this.doOutput(/*info*/ undefined, server.CommandNames.Configure, request.seq, /*success*/ true); return _this.notRequired(); }, _a[server.CommandNames.Reload] = function (request) { @@ -97394,6 +97766,10 @@ var ts; _a[server.CommandNames.GetCodeFixesFull] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false)); }, + _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { + _this.applyCodeActionCommand(request.command, request.seq, request.arguments); + return _this.notRequired(); // Response will come asynchronously. + }, _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, @@ -97502,9 +97878,9 @@ var ts; Session.prototype.logError = function (err, cmd) { var msg = "Exception on executing command " + cmd; if (err.message) { - msg += ":\n" + err.message; + msg += ":\n" + server.indent(err.message); if (err.stack) { - msg += "\n" + err.stack; + msg += "\n" + server.indent(err.stack); } } this.logger.msg(msg, server.Msg.Err); @@ -97527,20 +97903,26 @@ var ts; }; this.send(ev); }; + // For backwards-compatibility only. Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { - if (reqSeq === void 0) { reqSeq = 0; } + this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); + }; + Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) { var res = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, - success: !errorMsg, + success: success, }; - if (!errorMsg) { + if (success) { res.body = info; } else { - res.message = errorMsg; + ts.Debug.assert(info === undefined); + } + if (message) { + res.message = message; } this.send(res); }; @@ -98188,9 +98570,10 @@ var ts; if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction; var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; + // Use `hasAction || undefined` to avoid serializing `false`. + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined }; } }).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } @@ -98199,10 +98582,20 @@ var ts; } }; Session.prototype.getCompletionEntryDetails = function (args) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var position = this.getPositionInFile(args, file); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var formattingOptions = project.projectService.getFormatCodeOptions(file); return ts.mapDefined(args.entryNames, function (entryName) { - return project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName, formattingOptions); + if (details) { + var mappedCodeActions = ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action, scriptInfo); }); + return __assign({}, details, { codeActions: mappedCodeActions }); + } + else { + return undefined; + } }); }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { @@ -98296,7 +98689,7 @@ var ts; this.changeSeq++; // make sure no changes happen before this one is finished if (project.reloadScript(file, tempFileName)) { - this.output(undefined, server.CommandNames.Reload, reqSeq); + this.doOutput(/*info*/ undefined, server.CommandNames.Reload, reqSeq, /*success*/ true); } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { @@ -98500,6 +98893,16 @@ var ts; return codeActions; } }; + Session.prototype.applyCodeActionCommand = function (commandName, requestSeq, args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var output = function (success, message) { return _this.doOutput({}, commandName, requestSeq, success, message); }; + var command = args.command; // They should be sending back the command we sent them. + project.getLanguageService().applyCodeActionCommand(file, command).then(function (_a) { + var successMessage = _a.successMessage; + output(/*success*/ true, successMessage); + }, function (error) { output(/*success*/ false, error); }); + }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { var startPosition = undefined, endPosition = undefined; if (args.startPosition !== undefined) { @@ -98519,15 +98922,14 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + Session.prototype.mapCodeAction = function (_a, 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); }) - }); }) - }; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands; + var changes = unmappedChanges.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }); + return { description: description, changes: changes, commands: commands }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -98642,8 +99044,8 @@ var ts; return this.executeWithRequestId(request.seq, function () { return handler(request); }); } else { - this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); - this.output(undefined, server.CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); + this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err); + this.doOutput(/*info*/ undefined, server.CommandNames.Unknown, request.seq, /*success*/ false, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; @@ -98653,7 +99055,7 @@ var ts; if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("request: " + message); + this.logger.info("request:" + server.indent(message)); } } var request; @@ -98670,20 +99072,22 @@ var ts; } } if (response) { - this.output(response, request.command, request.seq); + this.doOutput(response, request.command, request.seq, /*success*/ true); } else if (responseRequired) { - this.output(undefined, request.command, request.seq, "No content available."); + this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ false, "No content available."); } } catch (err) { if (err instanceof ts.OperationCanceledException) { // Handle cancellation exceptions - this.output({ canceled: true }, request.command, request.seq); + this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } this.logError(err, message); - this.output(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); + this.doOutput( + /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, + /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); } }; return Session; @@ -99811,6 +100215,7 @@ var ts; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); /// +/* @internal */ var ts; (function (ts) { /** @@ -99825,7 +100230,7 @@ var ts; createNewValue: createMissingFileWatch, // Files that are no longer missing (e.g. because they are no longer required) // should no longer be watched. - onDeleteValue: ts.closeFileWatcher + onDeleteValue: closeFileWatcher }); } ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; @@ -99840,7 +100245,7 @@ var ts; // Create new watch and recursive info createNewValue: createWildcardDirectoryWatcher, // Close existing watch thats not needed any more - onDeleteValue: ts.closeFileWatcherOf, + onDeleteValue: closeFileWatcherOf, // Close existing watch that doesnt match in the flags onExistingValue: updateWildcardDirectoryWatcher }); @@ -99861,9 +100266,6 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -100145,6 +100547,30 @@ var ts; function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, + // When root is "/" do not watch directories like: + // "/", "/user", "/user/username", "/user/username/folderAtRoot" + // When root is "c:/" do not watch directories like: + // "c:/", "c:/folderAtRoot" + dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { return { dir: rootDir, dirPath: rootPath }; @@ -100158,7 +100584,7 @@ var ts; } // If the directory is node_modules use it to watch if (isNodeModulesDirectory(dirPath)) { - return { dir: dir, dirPath: dirPath }; + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } // Use some ancestor of the root directory if (rootPath !== undefined) { @@ -100171,7 +100597,7 @@ var ts; dir = ts.getDirectoryPath(dir); } } - return { dir: dir, dirPath: dirPath }; + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); @@ -100209,13 +100635,15 @@ var ts; var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); } - var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath; - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - if (dirWatcher) { - dirWatcher.refCount++; - } - else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + } } } } @@ -100239,10 +100667,12 @@ var ts; customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); } } - var dirPath = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath).dirPath; - var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); - // Do not close the watcher yet since it might be needed by other failed lookup locations. - dirWatcher.refCount--; + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } } } function createDirectoryWatcher(directory, dirPath) { @@ -100372,7 +100802,8 @@ var ts; return; } // we need to assume the directories exist to ensure that we can get all the type root directories that get included - var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: ts.returnTrue, getCurrentDirectory: getCurrentDirectory }); + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); if (typeRoots) { ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { createNewValue: createTypeRootsWatch, @@ -100383,6 +100814,16 @@ var ts; closeTypeRootsWatch(); } } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); @@ -100392,6 +100833,9 @@ var ts; var server; (function (server) { server.nullTypingsInstaller = { + isKnownTypesPackageName: ts.returnFalse, + // Should never be called because we never provide a types registry. + installPackage: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -100451,6 +100895,12 @@ var ts; this.installer = installer; this.perProjectCache = ts.createMap(); } + TypingsCache.prototype.isKnownTypesPackageName = function (name) { + return this.installer.isKnownTypesPackageName(name); + }; + TypingsCache.prototype.installPackage = function (options) { + return this.installer.installPackage(options); + }; TypingsCache.prototype.getTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -100667,6 +101117,19 @@ var ts; } return result.module; }; + Project.prototype.isKnownTypesPackageName = function (name) { + return this.typingsCache.isKnownTypesPackageName(name); + }; + Project.prototype.installPackage = function (options) { + return this.typingsCache.installPackage(__assign({}, options, { projectRootPath: this.toPath(this.currentDirectory) })); + }; + Object.defineProperty(Project.prototype, "typingsCache", { + get: function () { + return this.projectService.typingsCache; + }, + enumerable: true, + configurable: true + }); // Method of LanguageServiceHost Project.prototype.getCompilationSettings = function () { return this.compilerOptions; @@ -100814,32 +101277,30 @@ var ts; if (!this.builder) { this.builder = ts.createBuilder({ getCanonicalFileName: this.projectService.toCanonicalFileName, - getEmitOutput: function (_program, sourceFile, emitOnlyDts, isDetailed) { - return _this.getFileEmitOutput(sourceFile, emitOnlyDts, isDetailed); - }, - computeHash: function (data) { - return _this.projectService.host.createHash(data); - }, - shouldEmitFile: function (sourceFile) { - return !_this.projectService.getScriptInfoForPath(sourceFile.path).isDynamicOrHasMixedContent(); - } + computeHash: function (data) { return _this.projectService.host.createHash(data); } }); } }; + Project.prototype.shouldEmitFile = function (scriptInfo) { + return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); + }; Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + var _this = this; if (!this.languageServiceEnabled) { return []; } this.updateGraph(); this.ensureBuilder(); - return this.builder.getFilesAffectedBy(this.program, scriptInfo.path); + return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** * Returns true if emit was conducted */ Project.prototype.emitFile = function (scriptInfo, writeFile) { - this.ensureBuilder(); - var _a = this.builder.emitFile(this.program, scriptInfo.path), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { + return false; + } + var _a = this.getLanguageService(/*ensureSynchronized*/ false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; if (!emitSkipped) { for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { var outputFile = outputFiles_1[_i]; @@ -100951,12 +101412,6 @@ var ts; return scriptInfo; }); }; - Project.prototype.getFileEmitOutput = function (sourceFile, emitOnlyDtsFiles, isDetailed) { - if (!this.languageServiceEnabled) { - return undefined; - } - return this.getLanguageService(/*ensureSynchronized*/ false).getEmitOutput(sourceFile.fileName, emitOnlyDtsFiles, isDetailed); - }; Project.prototype.getExcludedFiles = function () { return server.emptyArray; }; @@ -101229,14 +101684,14 @@ var ts; return this.missingFilesMap && this.missingFilesMap.has(path); }; Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { - var scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, /*scriptKind*/ undefined, /*hasMixedContent*/ undefined, this.directoryStructureHost); + var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(fileName); if (scriptInfo && !scriptInfo.isAttached(this)) { return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); } return scriptInfo; }; Project.prototype.getScriptInfo = function (uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + return this.projectService.getScriptInfo(uncheckedFileName); }; Project.prototype.filesToString = function (writeProjectFileNames) { if (!this.program) { @@ -101245,8 +101700,8 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_10 = sourceFiles; _i < sourceFiles_10.length; _i++) { - var file = sourceFiles_10[_i]; + for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { + var file = sourceFiles_9[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -101430,8 +101885,8 @@ var ts; var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; _this.plugins = []; - /** Used for configured projects which may have multiple open roots */ - _this.openRefCount = 0; + /** Ref count to the project when opened from external project */ + _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); _this.enablePlugins(); return _this; @@ -101604,15 +102059,36 @@ var ts; this.configFileSpecs = undefined; _super.prototype.close.call(this); }; - ConfiguredProject.prototype.addOpenRef = function () { - this.openRefCount++; + /* @internal */ + ConfiguredProject.prototype.addExternalProjectReference = function () { + this.externalProjectRefCount++; }; - ConfiguredProject.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; + /* @internal */ + ConfiguredProject.prototype.deleteExternalProjectReference = function () { + this.externalProjectRefCount--; }; + /** Returns true if the project is needed by any of the open script info/external project */ + /* @internal */ ConfiguredProject.prototype.hasOpenRef = function () { - return !!this.openRefCount; + var _this = this; + if (!!this.externalProjectRefCount) { + return true; + } + // Closed project doesnt have any reference + if (this.isClosed()) { + return false; + } + var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + if (this.projectService.hasPendingProjectUpdate(this)) { + // If there is pending update for this project, + // we dont know if this project would be needed by any of the open files impacted by this config file + // In that case keep the project alive if there are open files impacted by this project + return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; + } + // If there is no pending update for this project, + // We know exact set of open files that get impacted by this configured project as the files in the project + // The project is referenced only if open files impacted by this project are present in this project + return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; @@ -101810,7 +102286,22 @@ var ts; server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, - getScriptKind: function (_) { return undefined; }, + getScriptKind: function (fileName, extraFileExtensions) { + var result; + if (extraFileExtensions) { + var fileExtension_1 = ts.getAnyExtensionFromPath(fileName); + if (fileExtension_1) { + ts.some(extraFileExtensions, function (info) { + if (info.extension === fileExtension_1) { + result = info.scriptKind; + return true; + } + return false; + }); + } + } + return result; + }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, }; var externalFilePropertyReader = { @@ -102037,6 +102528,10 @@ var ts; } }); }; + /*@internal*/ + ProjectService.prototype.hasPendingProjectUpdate = function (project) { + return this.pendingProjectUpdates.has(project.getProjectName()); + }; ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () { if (!this.eventHandler) { return; @@ -102249,8 +102744,13 @@ var ts; } }, flags, "Wild card directory" /* WildcardDirectories */, project); }; + /** Gets the config file existence info for the configured project */ + /*@internal*/ + ProjectService.prototype.getConfigFileExistenceInfo = function (project) { + return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + }; ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (eventKind === ts.FileWatcherEventKind.Deleted) { // Update the cached status // We arent updating or removing the cached config file presence info as that will be taken care of by @@ -102341,17 +102841,6 @@ var ts; } return project; }; - ProjectService.prototype.addToListOfOpenFiles = function (info) { - ts.Debug.assert(!info.isOrphan()); - for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { - var p = _a[_i]; - // file is the part of configured project, addref the project - if (p.projectKind === server.ProjectKind.Configured) { - (p).addOpenRef(); - } - } - this.openFiles.push(info); - }; /** * Remove this file from the set of open, non-configured files. * @param info The file that has been closed or newly configured @@ -102372,10 +102861,8 @@ var ts; if (info.hasMixedContent) { info.registerFileUpdate(); } - // Delete the reference to the open configured projects but - // do not remove the project so that we can reuse this project + // Do not remove the project so that we can reuse this project // if it would need to be re-created with next file open - p.deleteOpenRef(); } else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { // If this was the open root file of inferred project @@ -102458,7 +102945,7 @@ var ts; return exists; }; ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (configFileExistenceInfo) { ts.Debug.assert(configFileExistenceInfo.exists); // close existing watcher @@ -102485,7 +102972,7 @@ var ts; return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject, __key) { return isRootOfInferredProject; }); }; ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(closedProject.canonicalConfigFilePath); + var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); ts.Debug.assert(!!configFileExistenceInfo); if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { var configFileName = closedProject.getConfigFilePath(); @@ -102727,10 +103214,10 @@ var ts; var projectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw["extends"] !== undefined, - configHasFilesProperty: parsedCommandLine.raw["files"] !== undefined, - configHasIncludeProperty: parsedCommandLine.raw["include"] !== undefined, - configHasExcludeProperty: parsedCommandLine.raw["exclude"] !== undefined, + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, compileOnSave: parsedCommandLine.compileOnSave @@ -102859,7 +103346,7 @@ var ts; scriptInfo = normalizedPath; } else { - var scriptKind = propertyReader.getScriptKind(f); + var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, scriptKind, hasMixedContent, project.directoryStructureHost); path = scriptInfo.path; @@ -103257,7 +103744,8 @@ var ts; sendConfigFileDiagEvent = false; this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); } - this.addToListOfOpenFiles(info); + ts.Debug.assert(!info.isOrphan()); + this.openFiles.push(info); if (sendConfigFileDiagEvent) { configFileErrors = project.getAllProjectErrors(); this.sendConfigFileDiagEvent(project, fileName); @@ -103352,11 +103840,14 @@ var ts; this.changedFiles.push(scriptInfo); } }; - ProjectService.prototype.closeConfiguredProject = function (configFile) { + ProjectService.prototype.closeConfiguredProjectReferencedFromExternalProject = function (configFile) { var configuredProject = this.findConfiguredProjectByProjectName(configFile); - if (configuredProject && configuredProject.deleteOpenRef() === 0) { - this.removeProject(configuredProject); - return true; + if (configuredProject) { + configuredProject.deleteExternalProjectReference(); + if (!configuredProject.hasOpenRef()) { + this.removeProject(configuredProject); + return true; + } } return false; }; @@ -103368,7 +103859,7 @@ var ts; var shouldRefreshInferredProjects = false; for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { var configFile = configFiles_1[_i]; - if (this.closeConfiguredProject(configFile)) { + if (this.closeConfiguredProjectReferencedFromExternalProject(configFile)) { shouldRefreshInferredProjects = true; } } @@ -103564,7 +104055,7 @@ var ts; var newConfig = tsConfigFiles[iNew]; var oldConfig = oldConfigFiles[iOld]; if (oldConfig < newConfig) { - this.closeConfiguredProject(oldConfig); + this.closeConfiguredProjectReferencedFromExternalProject(oldConfig); iOld++; } else if (oldConfig > newConfig) { @@ -103579,7 +104070,7 @@ var ts; } for (var i = iOld; i < oldConfigFiles.length; i++) { // projects for all remaining old config files should be closed - this.closeConfiguredProject(oldConfigFiles[i]); + this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]); } } } @@ -103595,7 +104086,7 @@ var ts; } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project - project.addOpenRef(); + project.addExternalProjectReference(); } } } @@ -104096,9 +104587,12 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions); + }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 14fae7d0d77a0..89591ca1886fb 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -2158,6 +2158,7 @@ declare namespace ts { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface DiagnosticMessage { key: string; @@ -3154,10 +3155,11 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @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 @@ -3676,17 +3678,11 @@ declare namespace ts { outputFiles: OutputFile[]; emitSkipped: boolean; } - interface EmitOutputDetailed extends EmitOutput { - diagnostics: Diagnostic[]; - sourceMaps: SourceMapData[]; - emittedSourceFiles: SourceFile[]; - } interface OutputFile { name: string; writeByteOrderMark: boolean; text: string; } - function getFileEmitOutput(program: Program, sourceFile: SourceFile, emitOnlyDtsFiles: boolean, isDetailed: boolean, cancellationToken?: CancellationToken, customTransformers?: CustomTransformers): EmitOutput | EmitOutputDetailed; } declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; @@ -3868,7 +3864,11 @@ declare namespace ts { interface HostCancellationToken { isCancellationRequested(): boolean; } - interface LanguageServiceHost { + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { getCompilationSettings(): CompilerOptions; getNewLine?(): string; getProjectVersion?(): string; @@ -3890,12 +3890,13 @@ declare namespace ts { getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - directoryExists?(directoryName: string): boolean; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. */ getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; } interface LanguageService { cleanupSemanticCache(): void; @@ -3913,7 +3914,7 @@ declare namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, options?: FormatCodeOptions | FormatCodeSettings): CompletionEntryDetails; getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; @@ -3943,13 +3944,16 @@ declare namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, isDetailed?: boolean): EmitOutput | EmitOutputDetailed; getProgram(): Program; dispose(): void; } + interface ApplyCodeActionCommandResult { + successMessage: string; + } interface Classifications { spans: number[]; endOfLineState: EndOfLineState; @@ -4014,6 +4018,14 @@ declare namespace ts { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + type CodeActionCommand = InstallPackageAction; + interface InstallPackageAction { } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. @@ -4062,6 +4074,7 @@ declare namespace ts { edits: FileTextChanges[]; renameFilename: string | undefined; renameLocation: number | undefined; + commands?: CodeActionCommand[]; } interface TextInsertion { newText: string; @@ -4281,6 +4294,7 @@ declare namespace ts { * be used in that case */ replacementSpan?: TextSpan; + hasAction?: true; } interface CompletionEntryDetails { name: string; @@ -4289,6 +4303,7 @@ declare namespace ts { displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; tags: JSDocTagInfo[]; + codeActions?: CodeAction[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ diff --git a/lib/typescript.js b/lib/typescript.js index 654b1d2a53b2c..7cd3f6316ebef 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1386,8 +1386,8 @@ var ts; // Using 'delete' on an object causes V8 to put the object in dictionary mode. // This disables creation of hidden classes, which are expensive when an object is // constantly changing shape. - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } /** Create a new map. If a template object is provided, the map will copy entries from it. */ @@ -1527,6 +1527,17 @@ var ts; return undefined; } ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1585,6 +1596,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { @@ -2415,6 +2436,15 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -3785,6 +3815,16 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3936,8 +3976,13 @@ var ts; if (parentResult) { var baseName = getBaseNameOfFileName(fileOrDirectory); if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, baseName, host.fileExists(fileOrDirectoryPath)); - updateFileSystemEntry(parentResult.directories, baseName, host.directoryExists(fileOrDirectoryPath)); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + updateFileSystemEntry(parentResult.directories, baseName, fsQueryResult.directoryExists); + return fsQueryResult; } } } @@ -4002,7 +4047,7 @@ var ts; var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); // One file can have multiple watchers @@ -4401,7 +4446,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -5362,9 +5407,9 @@ var ts; Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), 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: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "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: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\"."), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\"."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), @@ -7658,6 +7703,17 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + /* @internal */ + function isAnyImportSyntax(node) { + switch (node.kind) { + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -8464,6 +8520,14 @@ var ts; return node && !!(node.flags & 1048576 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). @@ -8488,6 +8552,10 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(string, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, string).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; /** * Returns true if the node is a variable declaration whose initializer is a function expression. * This function does not test if the node is in a JavaScript file or not. @@ -18747,8 +18815,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -18885,8 +18953,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -23286,6 +23354,7 @@ var ts; loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); } + /* @internal */ function getPackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { @@ -23293,6 +23362,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); } @@ -23339,18 +23409,26 @@ var ts; /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); // Take off the "@" - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" } } - return moduleName; + return packageName; } /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { @@ -23726,6 +23804,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -29870,13 +29949,11 @@ var ts; function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -30731,7 +30808,7 @@ var ts; } var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; + spread.flags |= 1048576 /* FreshLiteral */ | 4194304 /* ContainsObjectLiteral */; spread.objectFlags |= 128 /* ObjectLiteral */; spread.symbol = symbol; return spread; @@ -33911,6 +33988,16 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { + if (type.flags & 524288 /* IndexedAccess */) { + // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to + // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -37244,7 +37331,7 @@ var ts; return unknownType; } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); + markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -37421,12 +37508,19 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -40974,7 +41068,10 @@ var ts; // There is no resolved symbol cached if the type resolved to a builtin // via JSDoc type reference resolution (eg, Boolean became boolean), none // of which are generic when they have no associated symbol - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + // (additionally, JSDoc's index signature syntax, Object actually uses generic syntax without being generic) + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; @@ -42345,7 +42442,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined); // A destructuring is never a write-only reference. + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -46719,13 +46816,16 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -70818,44 +70918,30 @@ var ts; })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); /// +/* @internal */ var ts; (function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; - var emittedSourceFiles; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - if (!isDetailed) { - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - } - return { - outputFiles: outputFiles, - emitSkipped: emitResult.emitSkipped, - diagnostics: emitResult.diagnostics, - sourceMaps: emitResult.sourceMaps, - emittedSourceFiles: emittedSourceFiles - }; - function writeFile(fileName, text, writeByteOrderMark, _onError, sourceFiles) { + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - if (isDetailed) { - emittedSourceFiles = ts.addRange(emittedSourceFiles, sourceFiles); - } } } ts.getFileEmitOutput = getFileEmitOutput; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { function createBuilder(options) { var isModuleEmit; var fileInfos = ts.createMap(); var semanticDiagnosticsPerFile = ts.createMap(); /** The map has key by source file's path that has been changed */ - var changedFileNames = ts.createMap(); + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; var emitHandler; return { updateProgram: updateProgram, getFilesAffectedBy: getFilesAffectedBy, - emitFile: emitFile, emitChangedFiles: emitChangedFiles, getSemanticDiagnostics: getSemanticDiagnostics, clear: clear @@ -70868,6 +70954,8 @@ var ts; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { // Add new file info createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, @@ -70877,28 +70965,31 @@ var ts; onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } }); } - function registerChangedFile(path, fileName) { - changedFileNames.set(path, fileName); + function registerChangedFile(path) { + changedFilesSet.set(path, true); // All changed files need to re-evaluate its semantic diagnostics semanticDiagnosticsPerFile.delete(path); } function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); emitHandler.onAddSourceFile(program, sourceFile); - return { fileName: sourceFile.fileName, version: sourceFile.version, signature: undefined }; + return { version: sourceFile.version, signature: undefined }; } - function removeExistingFileInfo(existingFileInfo, path) { - registerChangedFile(path, existingFileInfo.fileName); + function removeExistingFileInfo(_existingFileInfo, path) { + // Since we dont need to track removed file as changed file + // We can just remove its diagnostics + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); emitHandler.onRemoveSourceFile(path); } function updateExistingFileInfo(program, existingInfo, sourceFile) { if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); } } function ensureProgramGraph(program) { @@ -70913,93 +71004,80 @@ var ts; } function getFilesAffectedBy(program, path) { ensureProgramGraph(program); - var sourceFile = program.getSourceFile(path); - var singleFileResult = sourceFile && options.shouldEmitFile(sourceFile) ? [sourceFile.fileName] : []; - var info = fileInfos.get(path); - if (!info || !updateShapeSignature(program, sourceFile, info)) { - return singleFileResult; + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; } - ts.Debug.assert(!!sourceFile); - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult); + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); } - function emitFile(program, path) { + function emitChangedFiles(program, writeFileCallback) { ensureProgramGraph(program); - if (!fileInfos.has(path)) { - return { outputFiles: [], emitSkipped: true }; + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + // With --out or --outFile all outputs go into single file, do it only once + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; } - return options.getEmitOutput(program, program.getSourceFileByPath(path), /*emitOnlyDtsFiles*/ false, /*isDetailed*/ false); - } - function enumerateChangedFilesSet(program, onChangedFile, onAffectedFile) { - changedFileNames.forEach(function (fileName, path) { - onChangedFile(fileName, path); - var affectedFiles = getFilesAffectedBy(program, path); - for (var _i = 0, affectedFiles_1 = affectedFiles; _i < affectedFiles_1.length; _i++) { - var file = affectedFiles_1[_i]; - onAffectedFile(file, program.getSourceFile(file)); - } - }); - } - function enumerateChangedFilesEmitOutput(program, emitOnlyDtsFiles, onChangedFile, onEmitOutput) { var seenFiles = ts.createMap(); - enumerateChangedFilesSet(program, onChangedFile, function (fileName, sourceFile) { - if (!seenFiles.has(fileName)) { - seenFiles.set(fileName, true); - if (sourceFile) { - // Any affected file shouldnt have the cached diagnostics - semanticDiagnosticsPerFile.delete(sourceFile.path); - var emitOutput = options.getEmitOutput(program, sourceFile, emitOnlyDtsFiles, /*isDetailed*/ true); - onEmitOutput(emitOutput, sourceFile); - // mark all the emitted source files as seen - if (emitOutput.emittedSourceFiles) { - for (var _i = 0, _a = emitOutput.emittedSourceFiles; _i < _a.length; _i++) { - var file = _a[_i]; - seenFiles.set(file.fileName, true); - } - } + var result; + changedFilesSet.forEach(function (_true, path) { + // Get the affected Files by this program + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + // Affected files shouldnt have cached diagnostics + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + // Emit the affected file + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); } - } + }); }); - } - function emitChangedFiles(program) { - ensureProgramGraph(program); - var result = []; - enumerateChangedFilesEmitOutput(program, /*emitOnlyDtsFiles*/ false, - /*onChangedFile*/ ts.noop, function (emitOutput) { return result.push(emitOutput); }); - changedFileNames.clear(); - return result; + changedFilesSet.clear(); + return result || ts.emptyArray; } function getSemanticDiagnostics(program, cancellationToken) { ensureProgramGraph(program); - // Ensure that changed files have cleared their respective - enumerateChangedFilesSet(program, /*onChangedFile*/ ts.noop, function (_affectedFileName, sourceFile) { - if (sourceFile) { - semanticDiagnosticsPerFile.delete(sourceFile.path); - } - }); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + // We dont need to cache the diagnostics just return them from program + return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } var diagnostics; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - diagnostics = ts.addRange(diagnostics, cachedDiagnostics); - } - else { - // Diagnostics werent cached, get them from program, and cache the result - var cachedDiagnostics_1 = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, cachedDiagnostics_1); - diagnostics = ts.addRange(diagnostics, cachedDiagnostics_1); - } + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); } return diagnostics || ts.emptyArray; } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } function clear() { isModuleEmit = undefined; emitHandler = undefined; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); - changedFileNames.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); } /** * For script files that contains only ambient external modules, although they are not actually external module files, @@ -71019,15 +71097,23 @@ var ts; /** * @return {boolean} indicates if the shape signature has changed since last update. */ - function updateShapeSignature(program, sourceFile, info) { + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { - latestSignature = options.computeHash(sourceFile.text); + latestSignature = sourceFile.version; info.signature = latestSignature; } else { - var emitOutput = options.getEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true, /*isDetailed*/ false); + var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = options.computeHash(emitOutput.outputFiles[0].text); info.signature = latestSignature; @@ -71088,24 +71174,26 @@ var ts; } } /** - * Gets all the emittable files from the program. - * @param firstSourceFile This one will be emitted first. See https://github.com/Microsoft/TypeScript/issues/16888 + * Gets all files of the program excluding the default library file */ - function getAllEmittableFiles(program, firstSourceFile) { - var defaultLibraryFileName = ts.getDefaultLibFileName(program.getCompilerOptions()); - var sourceFiles = program.getSourceFiles(); - var result = []; - add(firstSourceFile); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + // Use cached result + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; if (sourceFile !== firstSourceFile) { - add(sourceFile); + addSourceFile(sourceFile); } } - return result; - function add(sourceFile) { - if (ts.getBaseFileName(sourceFile.fileName) !== defaultLibraryFileName && options.shouldEmitFile(sourceFile)) { - result.push(sourceFile.fileName); + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); } } } @@ -71117,14 +71205,14 @@ var ts; onUpdateSourceFileWithSameVersion: ts.returnFalse, getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape }; - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { var options = program.getCompilerOptions(); // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, // so returning the file itself is good enough. if (options && (options.out || options.outFile)) { - return singleFileResult; + return [sourceFile]; } - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } } function getModuleEmitHandler() { @@ -71174,7 +71262,7 @@ var ts; // add files referencing the removedFilePath, as changed files too var referencedByInfo = fileInfos.get(filePath); if (referencedByInfo) { - registerChangedFile(filePath, referencedByInfo.fileName); + registerChangedFile(filePath); } } }); @@ -71187,33 +71275,30 @@ var ts; return referencesInFile.has(referencedFilePath) ? filePath : undefined; }); } - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } var compilerOptions = program.getCompilerOptions(); if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return singleFileResult; + return [sourceFile]; } // Now we need to if each file in the referencedBy list has a shape change as well. // Because if so, its own referencedBy files need to be saved as well to make the // emitting result consistent with files on disk. var seenFileNamesMap = ts.createMap(); - var setSeenFileName = function (path, sourceFile) { - seenFileNamesMap.set(path, sourceFile && options.shouldEmitFile(sourceFile) ? sourceFile.fileName : undefined); - }; // Start with the paths this file was referenced by var path = sourceFile.path; - setSeenFileName(path, sourceFile); + seenFileNamesMap.set(path, sourceFile); var queue = getReferencedByPaths(path); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = program.getSourceFileByPath(currentPath); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile, fileInfos.get(currentPath))) { + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { queue.push.apply(queue, getReferencedByPaths(currentPath)); } - setSeenFileName(currentPath, currentSourceFile); } } // Return array of values that needs emit @@ -72300,8 +72385,9 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - // For JavaScript files, we don't want to report semantic errors unless explicitly requested. - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || ts.isCheckJsEnabledForFile(sourceFile, options); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -72938,8 +73024,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var file = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var file = sourceFiles_2[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -72950,8 +73036,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -74369,7 +74455,7 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 /* StringLiteral */ && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34 /* doubleQuote */; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { @@ -74608,9 +74694,9 @@ var ts; }; function getFileNames() { var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - filesSpecs = raw["files"]; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } @@ -74620,25 +74706,25 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } @@ -74718,7 +74804,7 @@ var ts; var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, 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 typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { @@ -74836,7 +74922,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -76743,9 +76829,7 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -76766,6 +76850,10 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -78232,18 +78320,18 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, @@ -78271,14 +78359,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -78334,7 +78422,7 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, symbolToOriginInfoMap) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { @@ -78344,6 +78432,9 @@ var ts; if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { + if (symbolToOriginInfoMap && symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, typeChecker)]) { + entry.hasAction = true; + } entries.push(entry); uniqueNames.set(id, true); } @@ -78488,46 +78579,61 @@ var ts; } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, name, allSourceFiles, host, rulesProvider) { // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (completionData) { - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; // 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(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === entryName ? s : undefined; }); + var symbol = ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === name; }); if (symbol) { + var codeActions = getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, rulesProvider); + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions }; } } // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; }); if (keywordCompletion) { return { - name: entryName, + name: name, kind: "keyword" /* keyword */, kindModifiers: "" /* none */, - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, - tags: undefined + tags: undefined, + codeActions: undefined, }; } return undefined; } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + function getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, rulesProvider) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, checker)]; + if (!symbolOriginInfo) { + return undefined; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + return ts.codefix.getCodeActionForImport(moduleSymbol, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + rulesProvider: rulesProvider, + symbolName: symbol.name, + getCanonicalFileName: ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false), + symbolToken: undefined, + kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, + }); + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName, allSourceFiles) { // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } @@ -78536,10 +78642,10 @@ var ts; // 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(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName ? s : undefined; }); + return ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var request; var start = ts.timestamp(); @@ -78604,7 +78710,18 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; + return { + symbols: undefined, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0 /* None */, + symbolToOriginInfoMap: undefined, + }; } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -78695,6 +78812,7 @@ var ts; var isNewIdentifierLocation; var keywordFilters = 0 /* None */; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } @@ -78727,7 +78845,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 279 /* JSDocParameterTag */: @@ -78881,11 +78999,13 @@ var ts; ts.isStatement(scopeNode); } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : ""); + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { @@ -78946,6 +79066,53 @@ var ts; return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var symbolIdMap = ts.arrayToNumericMap(symbols, function (s) { return ts.getUniqueSymbolId(s, typeChecker); }); + ts.codefix.forEachExternalModule(typeChecker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + } + var id = ts.getUniqueSymbolId(symbol, typeChecker); + if (!symbolIdMap[id] && stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[id] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -79640,7 +79807,7 @@ var ts; // First check of the displayName is not external module; if it is an external module, it is not valid entry if (symbol.flags & 1920 /* Namespace */) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; @@ -80680,8 +80847,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 265 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -80711,8 +80878,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -81297,19 +81464,25 @@ var ts; var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + if (node.kind === 79 /* DefaultKeyword */) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; @@ -81617,8 +81790,8 @@ var ts; } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } @@ -82152,8 +82325,8 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); @@ -83290,6 +83463,66 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + 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 = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var MaxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > MaxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + MaxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + throw ts.Debug.fail(); // Shouldn't have called this. + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /* @internal */ @@ -83310,8 +83543,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var sourceFile = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); @@ -89216,22 +89449,22 @@ var ts; * It can be changed to side-table later if we decide that current design is too invasive. */ function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -89328,6 +89561,11 @@ var ts; ChangeTracker.fromContext = function (context) { return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; @@ -90229,6 +90467,42 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_module_0.code, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); // These errors should only happen on the module name. + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + // If !registry, registry not available yet, can't do anything. + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: "Install '" + typesPackageName + "'", + changes: [], + commands: [{ type: "install package", packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -90660,6 +90934,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -90763,483 +91038,470 @@ var ts; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName_2; - if (umdSymbol.flags & 2097152 /* Alias */) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName_2 = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455 /* Value */)); - symbolName_2 = symbol.name; - } - else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + rulesProvider: context.rulesProvider, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbol, context) { + var declarations = getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + var actions = []; + if (context.symbolToken) { + // 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. + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } - return getCodeActionForImport(symbol, symbolName_2, /*isDefault*/ false, /*isNamespaceImport*/ true); } - var candidateModules = 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)) { - candidateModules.push(otherSourceFile.symbol); - } + actions.push(getCodeActionForAddImport(moduleSymbol, context, declarations)); + return actions; + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 240 /* NamespaceImport */ ? namedBindings.name : undefined; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_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.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); - } - } - // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(name !== "default"); - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); - } + else { + return declaration.name; } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + } + // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238 /* ImportDeclaration */: - return parent; - case 248 /* ExternalModuleReference */: - return parent.parent; - default: - return undefined; - } - } - } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238 /* ImportDeclaration */: + return parent; + case 248 /* ExternalModuleReference */: + return parent.parent; + default: + ts.Debug.assert(parent.kind === 244 /* ExportDeclaration */); + // Ignore these, can't add imports to them. + return undefined; } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - 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); + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createImportClauseOfKind(kind, symbolName), createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - return [getCodeActionForNewImport()]; + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - 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_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* 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 (!isNamespaceImport && 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 fileTextChanges = 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], fileTextChanges, "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 === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); - } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); + }); + // 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. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + switch (kind) { + case 1 /* Default */: + return ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined); + case 2 /* Namespace */: + return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))); + case 0 /* Named */: + return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); + default: + ts.Debug.assertNever(kind); + } + } + function getModuleSpecifierForNewImport(sourceFile, moduleSymbol, options, getCanonicalFileName, host) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + return tryGetModuleNameFromAmbientModule(moduleSymbol) || + tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) || + tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) || + tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) || + options.rootDirs && tryGetModuleNameFromRootDirs(options.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName)); + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) { + if (!options.baseUrl) { + return undefined; + } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl, getCanonicalFileName); + if (!relativeName) { + return undefined; + } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + 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; } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); + 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 { - namespacePrefix = declaration.name.getText(); + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; } - 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], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; + } + return relativeName; + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1)); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // 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. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } - }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39 /* singleQuote */; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - 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 || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - 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); - } - } - } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; - } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; } - return undefined; - } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + else { + state = 3 /* PackageContent */; } - return fileName; - } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionForAddImport(moduleSymbol, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 238 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ctx.kind, declaration.importClause); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + }); + if (fromExistingImport) { + return fromExistingImport; + } + var moduleSpecifier = ts.firstDefined(declarations, moduleSpecifierFromAnyImport) + || getModuleSpecifierForNewImport(ctx.sourceFile, moduleSymbol, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return getCodeActionForNewImport(ctx, moduleSpecifier); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 238 /* ImportDeclaration */ + ? node.moduleSpecifier + : node.moduleReference.kind === 248 /* ExternalModuleReference */ + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, kind, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + var name = importClause.name, namedBindings = importClause.namedBindings; + switch (kind) { + case 1 /* Default */: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0 /* Named */: { + var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 241 /* NamedImports */ && namedBindings.elements.length !== 0) { + // There are already named imports; add another. + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 241 /* NamedImports */ && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); + }); } + return undefined; } + case 2 /* Namespace */: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + default: + ts.Debug.assertNever(kind); + } + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + /** + * 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, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", + /*moduleSpecifier*/ undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbolName = symbol.name; } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: 2 /* Namespace */ })); } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.escapedName === symbolName && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = ts.getUniqueSymbolId(localSymbol, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); + } + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol); + } + } + } + codefix.forEachExternalModule = forEachExternalModule; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91977,7 +92239,7 @@ var ts; if (!usageContext.properties) { usageContext.properties = ts.createUnderscoreEscapedMap(); } - var propertyUsageContext = {}; + var propertyUsageContext = usageContext.properties.get(name) || {}; inferTypeFromContext(parent, checker, propertyUsageContext); usageContext.properties.set(name, propertyUsageContext); } @@ -92028,7 +92290,7 @@ var ts; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); members_4.set(name, symbol); }); } @@ -92084,7 +92346,7 @@ var ts; symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); parameters.push(symbol); } - var returnType = getTypeFromUsageContext(callContext.returnType, checker); + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { @@ -92103,6 +92365,7 @@ var ts; /// /// /// +/// /// /// /// @@ -92118,55 +92381,66 @@ var ts; var ts; (function (ts) { var refactor; - (function (refactor_2) { + (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { var actionName = "annotate"; var annotateTypeFromJSDoc = { name: "Annotate with type from JSDoc", description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAnnotation, - getAvailableActions: getAvailableActions - }; - var annotateFunctionFromJSDoc = { - name: "Annotate with types from JSDoc", - description: ts.Diagnostics.Annotate_with_types_from_JSDoc.message, - getEditsForAction: getEditsForFunctionAnnotation, + getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }; - refactor_2.registerRefactor(annotateTypeFromJSDoc); - refactor_2.registerRefactor(annotateFunctionFromJSDoc); + refactor.registerRefactor(annotateTypeFromJSDoc); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; } var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); - var decl = ts.findAncestor(node, isDeclarationWithType); - if (!decl || decl.type) { - return undefined; - } - var jsdocType = ts.getJSDocType(decl); - var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); - var refactor = (isFunctionWithJSDoc || jsdocType && decl.kind === 146 /* Parameter */) ? annotateFunctionFromJSDoc : - jsdocType ? annotateTypeFromJSDoc : - undefined; - if (refactor) { + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: refactor.name, - description: refactor.description, + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, actions: [ { - description: refactor.description, + description: annotateTypeFromJSDoc.description, name: actionName } ] }]; } } - function getEditsForAnnotation(context, action) { + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { if (actionName !== action) { return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 146 /* Parameter */) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); var decl = ts.findAncestor(token, isDeclarationWithType); @@ -92184,10 +92458,7 @@ var ts; renameLocation: undefined }; } - function getEditsForFunctionAnnotation(context, action) { - if (actionName !== action) { - return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); - } + function getEditsForFunctionAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); @@ -92266,7 +92537,9 @@ var ts; case 159 /* TypeReference */: return transformJSDocTypeReference(node); default: - return ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; } } function transformJSDocOptionalType(node) { @@ -92293,6 +92566,9 @@ var ts; var name = node.typeName; var args = node.typeArguments; if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } var text = node.typeName.text; switch (node.typeName.text) { case "String": @@ -92317,7 +92593,18 @@ var ts; } return ts.createTypeReferenceNode(name, args); } - })(annotateWithTypeFromJSDoc = refactor_2.annotateWithTypeFromJSDoc || (refactor_2.annotateWithTypeFromJSDoc = {})); + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -92983,27 +93270,26 @@ var ts; : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 146 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. // Walk up to the closest parent of a place where we can logically put a sibling: // * Function declaration // * Class declaration or expression // * Module/namespace or source file - if (current !== start && isScope(current)) { - (scopes = scopes || []).push(current); - } - // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current && current.parent && current.parent.kind === 146 /* Parameter */) { - // Skip all the way to the outer scope of the function that declared this parameter - current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; - } - else { - current = current.parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 265 /* SourceFile */) { + return scopes; + } } } - return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; @@ -93070,13 +93356,7 @@ var ts; } function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; @@ -94113,9 +94393,73 @@ var ts; })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (context.program.getCompilerOptions().noImplicitAny) { + // Then it will be available via `fixCannotFindModule`. + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); // Should be defined if we said there was an action available. + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + if (ts.isStringLiteral(node) && isModuleIdentifier(node) && ts.getResolvedModule(file, node.text) === undefined) { + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, node.text); + } + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 238 /* ImportDeclaration */: + case 248 /* ExternalModuleReference */: + return true; + default: + return false; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /// +/// /// /// /// @@ -95016,7 +95360,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -95169,15 +95513,16 @@ var ts; } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles()); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, entryName, formattingOptions) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + var ruleProvider = formattingOptions ? getRuleProvider(formattingOptions) : undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles(), host, ruleProvider); } function getCompletionEntrySymbol(fileName, position, entryName) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -95326,11 +95671,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles, isDetailed) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } // Signature help /** @@ -95534,6 +95879,17 @@ var ts; return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); } + function applyCodeActionCommand(fileName, action) { + fileName = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: fileName, packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -95708,8 +96064,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), + host: host, rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -95762,6 +96119,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -96996,9 +97354,12 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions); + }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 89fe29530e1a5..c0fc9fdbfb0fa 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -2158,6 +2158,7 @@ declare namespace ts { interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; + scriptKind?: ScriptKind; } interface DiagnosticMessage { key: string; @@ -3154,10 +3155,11 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @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 @@ -3676,17 +3678,11 @@ declare namespace ts { outputFiles: OutputFile[]; emitSkipped: boolean; } - interface EmitOutputDetailed extends EmitOutput { - diagnostics: Diagnostic[]; - sourceMaps: SourceMapData[]; - emittedSourceFiles: SourceFile[]; - } interface OutputFile { name: string; writeByteOrderMark: boolean; text: string; } - function getFileEmitOutput(program: Program, sourceFile: SourceFile, emitOnlyDtsFiles: boolean, isDetailed: boolean, cancellationToken?: CancellationToken, customTransformers?: CustomTransformers): EmitOutput | EmitOutputDetailed; } declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; @@ -3868,7 +3864,11 @@ declare namespace ts { interface HostCancellationToken { isCancellationRequested(): boolean; } - interface LanguageServiceHost { + interface InstallPackageOptions { + fileName: Path; + packageName: string; + } + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { getCompilationSettings(): CompilerOptions; getNewLine?(): string; getProjectVersion?(): string; @@ -3890,12 +3890,13 @@ declare namespace ts { getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - directoryExists?(directoryName: string): boolean; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. */ getCustomTransformers?(): CustomTransformers | undefined; + isKnownTypesPackageName?(name: string): boolean; + installPackage?(options: InstallPackageOptions): Promise; } interface LanguageService { cleanupSemanticCache(): void; @@ -3913,7 +3914,7 @@ declare namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, options?: FormatCodeOptions | FormatCodeSettings): CompletionEntryDetails; getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; @@ -3943,13 +3944,16 @@ declare namespace ts { isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[]; + applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, isDetailed?: boolean): EmitOutput | EmitOutputDetailed; getProgram(): Program; dispose(): void; } + interface ApplyCodeActionCommandResult { + successMessage: string; + } interface Classifications { spans: number[]; endOfLineState: EndOfLineState; @@ -4014,6 +4018,14 @@ declare namespace ts { description: string; /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; + /** + * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. + * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. + */ + commands?: CodeActionCommand[]; + } + type CodeActionCommand = InstallPackageAction; + interface InstallPackageAction { } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. @@ -4062,6 +4074,7 @@ declare namespace ts { edits: FileTextChanges[]; renameFilename: string | undefined; renameLocation: number | undefined; + commands?: CodeActionCommand[]; } interface TextInsertion { newText: string; @@ -4281,6 +4294,7 @@ declare namespace ts { * be used in that case */ replacementSpan?: TextSpan; + hasAction?: true; } interface CompletionEntryDetails { name: string; @@ -4289,6 +4303,7 @@ declare namespace ts { displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; tags: JSDocTagInfo[]; + codeActions?: CodeAction[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 654b1d2a53b2c..7cd3f6316ebef 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1386,8 +1386,8 @@ var ts; // Using 'delete' on an object causes V8 to put the object in dictionary mode. // This disables creation of hidden classes, which are expensive when an object is // constantly changing shape. - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } /** Create a new map. If a template object is provided, the map will copy entries from it. */ @@ -1527,6 +1527,17 @@ var ts; return undefined; } ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1585,6 +1596,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { @@ -2415,6 +2436,15 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -3785,6 +3815,16 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -3936,8 +3976,13 @@ var ts; if (parentResult) { var baseName = getBaseNameOfFileName(fileOrDirectory); if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, baseName, host.fileExists(fileOrDirectoryPath)); - updateFileSystemEntry(parentResult.directories, baseName, host.directoryExists(fileOrDirectoryPath)); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + updateFileSystemEntry(parentResult.directories, baseName, fsQueryResult.directoryExists); + return fsQueryResult; } } } @@ -4002,7 +4047,7 @@ var ts; var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); // One file can have multiple watchers @@ -4401,7 +4446,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -5362,9 +5407,9 @@ var ts; Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), 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: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "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: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\"."), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\"."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), @@ -7658,6 +7703,17 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + /* @internal */ + function isAnyImportSyntax(node) { + switch (node.kind) { + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -8464,6 +8520,14 @@ var ts; return node && !!(node.flags & 1048576 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 /* StringKeyword */ || node.typeArguments[0].kind === 133 /* NumberKeyword */); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). @@ -8488,6 +8552,10 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(string, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, string).charCodeAt(0) === 34 /* doubleQuote */; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; /** * Returns true if the node is a variable declaration whose initializer is a function expression. * This function does not test if the node is in a JavaScript file or not. @@ -18747,8 +18815,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -18885,8 +18953,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -23286,6 +23354,7 @@ var ts; loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); return withPackageId(packageId, pathAndExtension); } + /* @internal */ function getPackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { @@ -23293,6 +23362,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); } @@ -23339,18 +23409,26 @@ var ts; /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); // Take off the "@" - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + /* @internal */ + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); // Take off the "@" } } - return moduleName; + return packageName; } /* @internal */ function getPackageNameFromAtTypesDirectory(mangledName) { @@ -23726,6 +23804,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -29870,13 +29949,11 @@ var ts; function getIntendedTypeFromJSDocTypeReference(node) { if (ts.isIdentifier(node.typeName)) { if (node.typeName.escapedText === "Object") { - if (node.typeArguments && node.typeArguments.length === 2) { + if (ts.isJSDocIndexSignature(node)) { var indexed = getTypeFromTypeNode(node.typeArguments[0]); var target = getTypeFromTypeNode(node.typeArguments[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - if (indexed === stringType || indexed === numberType) { - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); - } + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); } return anyType; } @@ -30731,7 +30808,7 @@ var ts; } var spread = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; + spread.flags |= 1048576 /* FreshLiteral */ | 4194304 /* ContainsObjectLiteral */; spread.objectFlags |= 128 /* ObjectLiteral */; spread.symbol = symbol; return spread; @@ -33911,6 +33988,16 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { + if (type.flags & 524288 /* IndexedAccess */) { + // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to + // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior + var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; + var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); + if (result !== baseConstraint) { + return result; + } + return type; + } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -37244,7 +37331,7 @@ var ts; return unknownType; } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node); + markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -37421,12 +37508,19 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { + if (isThisAccess) { + // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). + var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); + if (containingMethod && containingMethod.symbol === prop) { + return; + } + } if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -40974,7 +41068,10 @@ var ts; // There is no resolved symbol cached if the type resolved to a builtin // via JSDoc type reference resolution (eg, Boolean became boolean), none // of which are generic when they have no associated symbol - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + // (additionally, JSDoc's index signature syntax, Object actually uses generic syntax without being generic) + if (!ts.isJSDocIndexSignature(node)) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + } return; } var typeParameters = symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters; @@ -42345,7 +42442,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined); // A destructuring is never a write-only reference. + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -46719,13 +46816,16 @@ var ts; } } function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { - result.push(global); - } - }); - return result; + if (!ambientModulesCache) { + ambientModulesCache = []; + globals.forEach(function (global, sym) { + // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. + if (ambientModuleSymbolRegex.test(sym)) { + ambientModulesCache.push(global); + } + }); + } + return ambientModulesCache; } function checkGrammarImportCallExpression(node) { if (modulekind === ts.ModuleKind.ES2015) { @@ -70818,44 +70918,30 @@ var ts; })(ListFormat || (ListFormat = {})); })(ts || (ts = {})); /// +/* @internal */ var ts; (function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { var outputFiles = []; - var emittedSourceFiles; var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - if (!isDetailed) { - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - } - return { - outputFiles: outputFiles, - emitSkipped: emitResult.emitSkipped, - diagnostics: emitResult.diagnostics, - sourceMaps: emitResult.sourceMaps, - emittedSourceFiles: emittedSourceFiles - }; - function writeFile(fileName, text, writeByteOrderMark, _onError, sourceFiles) { + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - if (isDetailed) { - emittedSourceFiles = ts.addRange(emittedSourceFiles, sourceFiles); - } } } ts.getFileEmitOutput = getFileEmitOutput; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { function createBuilder(options) { var isModuleEmit; var fileInfos = ts.createMap(); var semanticDiagnosticsPerFile = ts.createMap(); /** The map has key by source file's path that has been changed */ - var changedFileNames = ts.createMap(); + var changedFilesSet = ts.createMap(); + var hasShapeChanged = ts.createMap(); + var allFilesExcludingDefaultLibraryFile; var emitHandler; return { updateProgram: updateProgram, getFilesAffectedBy: getFilesAffectedBy, - emitFile: emitFile, emitChangedFiles: emitChangedFiles, getSemanticDiagnostics: getSemanticDiagnostics, clear: clear @@ -70868,6 +70954,8 @@ var ts; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); } + hasShapeChanged.clear(); + allFilesExcludingDefaultLibraryFile = undefined; ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { // Add new file info createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, @@ -70877,28 +70965,31 @@ var ts; onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } }); } - function registerChangedFile(path, fileName) { - changedFileNames.set(path, fileName); + function registerChangedFile(path) { + changedFilesSet.set(path, true); // All changed files need to re-evaluate its semantic diagnostics semanticDiagnosticsPerFile.delete(path); } function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); emitHandler.onAddSourceFile(program, sourceFile); - return { fileName: sourceFile.fileName, version: sourceFile.version, signature: undefined }; + return { version: sourceFile.version, signature: undefined }; } - function removeExistingFileInfo(existingFileInfo, path) { - registerChangedFile(path, existingFileInfo.fileName); + function removeExistingFileInfo(_existingFileInfo, path) { + // Since we dont need to track removed file as changed file + // We can just remove its diagnostics + changedFilesSet.delete(path); + semanticDiagnosticsPerFile.delete(path); emitHandler.onRemoveSourceFile(path); } function updateExistingFileInfo(program, existingInfo, sourceFile) { if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); existingInfo.version = sourceFile.version; emitHandler.onUpdateSourceFile(program, sourceFile); } else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path, sourceFile.fileName); + registerChangedFile(sourceFile.path); } } function ensureProgramGraph(program) { @@ -70913,93 +71004,80 @@ var ts; } function getFilesAffectedBy(program, path) { ensureProgramGraph(program); - var sourceFile = program.getSourceFile(path); - var singleFileResult = sourceFile && options.shouldEmitFile(sourceFile) ? [sourceFile.fileName] : []; - var info = fileInfos.get(path); - if (!info || !updateShapeSignature(program, sourceFile, info)) { - return singleFileResult; + var sourceFile = program.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; } - ts.Debug.assert(!!sourceFile); - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult); + if (!updateShapeSignature(program, sourceFile)) { + return [sourceFile]; + } + return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); } - function emitFile(program, path) { + function emitChangedFiles(program, writeFileCallback) { ensureProgramGraph(program); - if (!fileInfos.has(path)) { - return { outputFiles: [], emitSkipped: true }; + var compilerOptions = program.getCompilerOptions(); + if (!changedFilesSet.size) { + return ts.emptyArray; + } + // With --out or --outFile all outputs go into single file, do it only once + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + changedFilesSet.clear(); + return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; } - return options.getEmitOutput(program, program.getSourceFileByPath(path), /*emitOnlyDtsFiles*/ false, /*isDetailed*/ false); - } - function enumerateChangedFilesSet(program, onChangedFile, onAffectedFile) { - changedFileNames.forEach(function (fileName, path) { - onChangedFile(fileName, path); - var affectedFiles = getFilesAffectedBy(program, path); - for (var _i = 0, affectedFiles_1 = affectedFiles; _i < affectedFiles_1.length; _i++) { - var file = affectedFiles_1[_i]; - onAffectedFile(file, program.getSourceFile(file)); - } - }); - } - function enumerateChangedFilesEmitOutput(program, emitOnlyDtsFiles, onChangedFile, onEmitOutput) { var seenFiles = ts.createMap(); - enumerateChangedFilesSet(program, onChangedFile, function (fileName, sourceFile) { - if (!seenFiles.has(fileName)) { - seenFiles.set(fileName, true); - if (sourceFile) { - // Any affected file shouldnt have the cached diagnostics - semanticDiagnosticsPerFile.delete(sourceFile.path); - var emitOutput = options.getEmitOutput(program, sourceFile, emitOnlyDtsFiles, /*isDetailed*/ true); - onEmitOutput(emitOutput, sourceFile); - // mark all the emitted source files as seen - if (emitOutput.emittedSourceFiles) { - for (var _i = 0, _a = emitOutput.emittedSourceFiles; _i < _a.length; _i++) { - var file = _a[_i]; - seenFiles.set(file.fileName, true); - } - } + var result; + changedFilesSet.forEach(function (_true, path) { + // Get the affected Files by this program + var affectedFiles = getFilesAffectedBy(program, path); + affectedFiles.forEach(function (affectedFile) { + // Affected files shouldnt have cached diagnostics + semanticDiagnosticsPerFile.delete(affectedFile.path); + if (!seenFiles.has(affectedFile.path)) { + seenFiles.set(affectedFile.path, true); + // Emit the affected file + (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); } - } + }); }); - } - function emitChangedFiles(program) { - ensureProgramGraph(program); - var result = []; - enumerateChangedFilesEmitOutput(program, /*emitOnlyDtsFiles*/ false, - /*onChangedFile*/ ts.noop, function (emitOutput) { return result.push(emitOutput); }); - changedFileNames.clear(); - return result; + changedFilesSet.clear(); + return result || ts.emptyArray; } function getSemanticDiagnostics(program, cancellationToken) { ensureProgramGraph(program); - // Ensure that changed files have cleared their respective - enumerateChangedFilesSet(program, /*onChangedFile*/ ts.noop, function (_affectedFileName, sourceFile) { - if (sourceFile) { - semanticDiagnosticsPerFile.delete(sourceFile.path); - } - }); + ts.Debug.assert(changedFilesSet.size === 0); + var compilerOptions = program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); + // We dont need to cache the diagnostics just return them from program + return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } var diagnostics; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - diagnostics = ts.addRange(diagnostics, cachedDiagnostics); - } - else { - // Diagnostics werent cached, get them from program, and cache the result - var cachedDiagnostics_1 = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, cachedDiagnostics_1); - diagnostics = ts.addRange(diagnostics, cachedDiagnostics_1); - } + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); } return diagnostics || ts.emptyArray; } + function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } function clear() { isModuleEmit = undefined; emitHandler = undefined; fileInfos.clear(); semanticDiagnosticsPerFile.clear(); - changedFileNames.clear(); + changedFilesSet.clear(); + hasShapeChanged.clear(); } /** * For script files that contains only ambient external modules, although they are not actually external module files, @@ -71019,15 +71097,23 @@ var ts; /** * @return {boolean} indicates if the shape signature has changed since last update. */ - function updateShapeSignature(program, sourceFile, info) { + function updateShapeSignature(program, sourceFile) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (hasShapeChanged.has(sourceFile.path)) { + return false; + } + hasShapeChanged.set(sourceFile.path, true); + var info = fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); var prevSignature = info.signature; var latestSignature; if (sourceFile.isDeclarationFile) { - latestSignature = options.computeHash(sourceFile.text); + latestSignature = sourceFile.version; info.signature = latestSignature; } else { - var emitOutput = options.getEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true, /*isDetailed*/ false); + var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { latestSignature = options.computeHash(emitOutput.outputFiles[0].text); info.signature = latestSignature; @@ -71088,24 +71174,26 @@ var ts; } } /** - * Gets all the emittable files from the program. - * @param firstSourceFile This one will be emitted first. See https://github.com/Microsoft/TypeScript/issues/16888 + * Gets all files of the program excluding the default library file */ - function getAllEmittableFiles(program, firstSourceFile) { - var defaultLibraryFileName = ts.getDefaultLibFileName(program.getCompilerOptions()); - var sourceFiles = program.getSourceFiles(); - var result = []; - add(firstSourceFile); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { + // Use cached result + if (allFilesExcludingDefaultLibraryFile) { + return allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; if (sourceFile !== firstSourceFile) { - add(sourceFile); + addSourceFile(sourceFile); } } - return result; - function add(sourceFile) { - if (ts.getBaseFileName(sourceFile.fileName) !== defaultLibraryFileName && options.shouldEmitFile(sourceFile)) { - result.push(sourceFile.fileName); + allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); } } } @@ -71117,14 +71205,14 @@ var ts; onUpdateSourceFileWithSameVersion: ts.returnFalse, getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape }; - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { var options = program.getCompilerOptions(); // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, // so returning the file itself is good enough. if (options && (options.out || options.outFile)) { - return singleFileResult; + return [sourceFile]; } - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } } function getModuleEmitHandler() { @@ -71174,7 +71262,7 @@ var ts; // add files referencing the removedFilePath, as changed files too var referencedByInfo = fileInfos.get(filePath); if (referencedByInfo) { - registerChangedFile(filePath, referencedByInfo.fileName); + registerChangedFile(filePath); } } }); @@ -71187,33 +71275,30 @@ var ts; return referencesInFile.has(referencedFilePath) ? filePath : undefined; }); } - function getFilesAffectedByUpdatedShape(program, sourceFile, singleFileResult) { + function getFilesAffectedByUpdatedShape(program, sourceFile) { if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllEmittableFiles(program, sourceFile); + return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); } var compilerOptions = program.getCompilerOptions(); if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return singleFileResult; + return [sourceFile]; } // Now we need to if each file in the referencedBy list has a shape change as well. // Because if so, its own referencedBy files need to be saved as well to make the // emitting result consistent with files on disk. var seenFileNamesMap = ts.createMap(); - var setSeenFileName = function (path, sourceFile) { - seenFileNamesMap.set(path, sourceFile && options.shouldEmitFile(sourceFile) ? sourceFile.fileName : undefined); - }; // Start with the paths this file was referenced by var path = sourceFile.path; - setSeenFileName(path, sourceFile); + seenFileNamesMap.set(path, sourceFile); var queue = getReferencedByPaths(path); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = program.getSourceFileByPath(currentPath); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile, fileInfos.get(currentPath))) { + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { queue.push.apply(queue, getReferencedByPaths(currentPath)); } - setSeenFileName(currentPath, currentSourceFile); } } // Return array of values that needs emit @@ -72300,8 +72385,9 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - // For JavaScript files, we don't want to report semantic errors unless explicitly requested. - var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || ts.isCheckJsEnabledForFile(sourceFile, options); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); @@ -72938,8 +73024,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var file = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var file = sourceFiles_2[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -72950,8 +73036,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; if (!sourceFile.isDeclarationFile) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -74369,7 +74455,7 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 /* StringLiteral */ && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34 /* doubleQuote */; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { @@ -74608,9 +74694,9 @@ var ts; }; function getFileNames() { var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - filesSpecs = raw["files"]; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } @@ -74620,25 +74706,25 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } @@ -74718,7 +74804,7 @@ var ts; var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, 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 typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { @@ -74836,7 +74922,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -76743,9 +76829,7 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && - name.charCodeAt(0) === name.charCodeAt(length - 1) && - (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { return name.substring(1, length - 1); } return name; @@ -76766,6 +76850,10 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getUniqueSymbolId(symbol, checker) { + return ts.getSymbolId(ts.skipAlias(symbol, checker)); + } + ts.getUniqueSymbolId = getUniqueSymbolId; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -78232,18 +78320,18 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { + function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, @@ -78271,14 +78359,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -78334,7 +78422,7 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, symbolToOriginInfoMap) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { @@ -78344,6 +78432,9 @@ var ts; if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { + if (symbolToOriginInfoMap && symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, typeChecker)]) { + entry.hasAction = true; + } entries.push(entry); uniqueNames.set(id, true); } @@ -78488,46 +78579,61 @@ var ts; } } } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, name, allSourceFiles, host, rulesProvider) { // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (completionData) { - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap; // 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(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === entryName ? s : undefined; }); + var symbol = ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === name; }); if (symbol) { + var codeActions = getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, rulesProvider); + var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; - return { - name: entryName, - kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), - kind: symbolKind, - displayParts: displayParts, - documentation: documentation, - tags: tags - }; + return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions }; } } // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; }); if (keywordCompletion) { return { - name: entryName, + name: name, kind: "keyword" /* keyword */, kindModifiers: "" /* none */, - displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], + displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, - tags: undefined + tags: undefined, + codeActions: undefined, }; } return undefined; } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { + function getCompletionEntryCodeActions(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, rulesProvider) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getUniqueSymbolId(symbol, checker)]; + if (!symbolOriginInfo) { + return undefined; + } + var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; + return ts.codefix.getCodeActionForImport(moduleSymbol, { + host: host, + checker: checker, + newLineCharacter: host.getNewLine(), + compilerOptions: compilerOptions, + sourceFile: sourceFile, + rulesProvider: rulesProvider, + symbolName: symbol.name, + getCanonicalFileName: ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false), + symbolToken: undefined, + kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, + }); + } + function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName, allSourceFiles) { // Compute all the completion symbols again. - var completionData = getCompletionData(typeChecker, log, sourceFile, position); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles); if (!completionData) { return undefined; } @@ -78536,10 +78642,10 @@ var ts; // 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(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName ? s : undefined; }); + return ts.find(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getCompletionData(typeChecker, log, sourceFile, position) { + function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var request; var start = ts.timestamp(); @@ -78604,7 +78710,18 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; + return { + symbols: undefined, + isGlobalCompletion: false, + isMemberCompletion: false, + allowStringLiteral: false, + isNewIdentifierLocation: false, + location: undefined, + isRightOfDot: false, + request: request, + keywordFilters: 0 /* None */, + symbolToOriginInfoMap: undefined, + }; } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -78695,6 +78812,7 @@ var ts; var isNewIdentifierLocation; var keywordFilters = 0 /* None */; var symbols = []; + var symbolToOriginInfoMap = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); } @@ -78727,7 +78845,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 279 /* JSDocParameterTag */: @@ -78881,11 +78999,13 @@ var ts; ts.isStatement(scopeNode); } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; - symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : ""); + filterGlobalCompletion(symbols); return true; } function filterGlobalCompletion(symbols) { - return ts.filter(symbols, function (symbol) { + ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { @@ -78946,6 +79066,53 @@ var ts; return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); } } + function getSymbolsFromOtherSourceFileExports(symbols, tokenText) { + var tokenTextLowerCase = tokenText.toLowerCase(); + var symbolIdMap = ts.arrayToNumericMap(symbols, function (s) { return ts.getUniqueSymbolId(s, typeChecker); }); + ts.codefix.forEachExternalModule(typeChecker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var symbol = _a[_i]; + var name = symbol.name; + var isDefaultExport = name === "default"; + if (isDefaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(symbol); + if (localSymbol) { + symbol = localSymbol; + name = localSymbol.name; + } + } + var id = ts.getUniqueSymbolId(symbol, typeChecker); + if (!symbolIdMap[id] && stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + symbols.push(symbol); + symbolToOriginInfoMap[id] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + } + } + }); + } + /** + * True if you could remove some characters in `a` to get `b`. + * E.g., true for "abcdef" and "bdf". + * But not true for "abcdef" and "dbf". + */ + function stringContainsCharactersInOrder(str, characters) { + if (characters.length === 0) { + return true; + } + var characterIndex = 0; + for (var strIndex = 0; strIndex < str.length; strIndex++) { + if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { + characterIndex++; + if (characterIndex === characters.length) { + return true; + } + } + } + // Did not find all characters + return false; + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -79640,7 +79807,7 @@ var ts; // First check of the displayName is not external module; if it is an external module, it is not valid entry if (symbol.flags & 1920 /* Namespace */) { var firstCharCode = name.charCodeAt(0); - if (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */) { + if (ts.isSingleOrDoubleQuote(firstCharCode)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; @@ -80680,8 +80847,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var referencingFile = sourceFiles_4[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 265 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -80711,8 +80878,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); @@ -81297,19 +81464,25 @@ var ts; var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + if (node.kind === 79 /* DefaultKeyword */) { + addReference(node, symbol, node, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } } } return result; @@ -81617,8 +81790,8 @@ var ts; } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; cancellationToken.throwIfCancellationRequested(); addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references); } @@ -82152,8 +82325,8 @@ var ts; } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = []; - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; cancellationToken.throwIfCancellationRequested(); var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text); getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references); @@ -83290,6 +83463,66 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + 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 = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var MaxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > MaxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + MaxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + throw ts.Debug.fail(); // Shouldn't have called this. + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); /* @internal */ @@ -83310,8 +83543,8 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var sourceFile = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); @@ -89216,22 +89449,22 @@ var ts; * It can be changed to side-table later if we decide that current design is too invasive. */ function getPos(n) { - var result = n["__pos"]; + var result = n.__pos; ts.Debug.assert(typeof result === "number"); return result; } function setPos(n, pos) { ts.Debug.assert(typeof pos === "number"); - n["__pos"] = pos; + n.__pos = pos; } function getEnd(n) { - var result = n["__end"]; + var result = n.__end; ts.Debug.assert(typeof result === "number"); return result; } function setEnd(n, end) { ts.Debug.assert(typeof end === "number"); - n["__end"] = end; + n.__end = end; } var Position; (function (Position) { @@ -89328,6 +89561,11 @@ var ts; ChangeTracker.fromContext = function (context) { return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); }; + ChangeTracker.with = function (context, cb) { + var tracker = ChangeTracker.fromContext(context); + cb(tracker); + return tracker.getChanges(); + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; @@ -90229,6 +90467,42 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_find_module_0.code, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, start = context.span.start; + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + if (!ts.isStringLiteral(token)) { + throw ts.Debug.fail(); // These errors should only happen on the module name. + } + var action = tryGetCodeActionForInstallPackageTypes(context.host, token.text); + return action && [action]; + }, + }); + function tryGetCodeActionForInstallPackageTypes(host, moduleName) { + var packageName = ts.getPackageName(moduleName).packageName; + if (!host.isKnownTypesPackageName(packageName)) { + // If !registry, registry not available yet, can't do anything. + return undefined; + } + var typesPackageName = ts.getTypesPackageName(packageName); + return { + description: "Install '" + typesPackageName + "'", + changes: [], + commands: [{ type: "install package", packageName: typesPackageName }], + }; + } + codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -90660,6 +90934,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var ChangeTracker = ts.textChanges.ChangeTracker; codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Cannot_find_name_0.code, @@ -90763,483 +91038,470 @@ var ts; }; return ImportCodeActionMap; }()); - function getImportCodeActions(context) { - var sourceFile = context.sourceFile; - var checker = context.program.getTypeChecker(); - var allSourceFiles = context.program.getSourceFiles(); + function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { + return { + description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), + changes: changes, + kind: kind, + moduleSpecifier: moduleSpecifier + }; + } + function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var name = token.getText(); - var symbolIdActionMap = new ImportCodeActionMap(); - // this is a module id -> module import declaration map - var cachedImportDeclarations = []; - var lastImportDeclaration; - var currentTokenMeaning = ts.getMeaningFromLocation(token); - if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { - var umdSymbol = checker.getSymbolAtLocation(token); - var symbol = void 0; - var symbolName_2; - if (umdSymbol.flags & 2097152 /* Alias */) { - symbol = checker.getAliasedSymbol(umdSymbol); - symbolName_2 = name; - } - else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), token.parent.tagName, 107455 /* Value */)); - symbolName_2 = symbol.name; - } - else { - ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + var checker = context.program.getTypeChecker(); + var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + return { + host: context.host, + newLineCharacter: context.newLineCharacter, + rulesProvider: context.rulesProvider, + sourceFile: context.sourceFile, + checker: checker, + compilerOptions: context.program.getCompilerOptions(), + cachedImportDeclarations: [], + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + symbolName: symbolToken.getText(), + symbolToken: symbolToken, + }; + } + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + })(ImportKind = codefix.ImportKind || (codefix.ImportKind = {})); + function getCodeActionForImport(moduleSymbol, context) { + var declarations = getImportDeclarations(moduleSymbol, context.checker, context.sourceFile, context.cachedImportDeclarations); + var actions = []; + if (context.symbolToken) { + // 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. + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } - return getCodeActionForImport(symbol, symbolName_2, /*isDefault*/ false, /*isNamespaceImport*/ true); } - var candidateModules = 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)) { - candidateModules.push(otherSourceFile.symbol); - } + actions.push(getCodeActionForAddImport(moduleSymbol, context, declarations)); + return actions; + } + codefix.getCodeActionForImport = getCodeActionForImport; + function getNamespaceImportName(declaration) { + if (declaration.kind === 238 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 240 /* NamespaceImport */ ? namedBindings.name : undefined; } - for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) { - var moduleSymbol = candidateModules_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.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { - // check if this symbol is already used - var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); - } - } - // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(name !== "default"); - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); - } + else { + return declaration.name; } - return symbolIdActionMap.getAllActions(); - function getImportDeclarations(moduleSymbol) { - var moduleSymbolId = getUniqueSymbolId(moduleSymbol); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (cached) { - return cached; - } - var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + } + // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? + function getImportDeclarations(moduleSymbol, checker, _a, cachedImportDeclarations) { + var imports = _a.imports; + if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } + var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); + var cached = cachedImportDeclarations[moduleSymbolId]; + if (!cached) { + cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; }); - cachedImportDeclarations[moduleSymbolId] = existingDeclarations; - return existingDeclarations; - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 238 /* ImportDeclaration */: - return parent; - case 248 /* ExternalModuleReference */: - return parent.parent; - default: - return undefined; - } - } - } - function getUniqueSymbolId(symbol) { - return ts.getSymbolId(ts.skipAlias(symbol, checker)); } - function checkSymbolHasMeaning(symbol, meaning) { - var declarations = symbol.getDeclarations(); - return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false; + return cached; + } + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238 /* ImportDeclaration */: + return parent; + case 248 /* ExternalModuleReference */: + return parent.parent; + default: + ts.Debug.assert(parent.kind === 244 /* ExportDeclaration */); + // Ignore these, can't add imports to them. + return undefined; } - function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { - 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); + } + function getCodeActionForNewImport(context, moduleSpecifier) { + var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createImportClauseOfKind(kind, symbolName), createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes)); + var changes = ChangeTracker.with(context, function (changeTracker) { + if (lastImportDeclaration) { + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); } else { - return [getCodeActionForNewImport()]; + changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); } - 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_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; - if (declaration.kind === 238 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && declaration.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 240 /* 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 (!isNamespaceImport && 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 fileTextChanges = 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], fileTextChanges, "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 === 248 /* ExternalModuleReference */) { - return declaration.moduleReference.expression.getText(); - } - return declaration.moduleReference.getText(); - } - function getTextChangeForImportClause(importClause) { - var importList = importClause.namedBindings; - var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); - // case 1: - // original text: import default from "module" - // change to: import default, { name } from "module" - // case 2: - // original text: import {} from "module" - // change to: import { name } from "module" - if (!importList || importList.elements.length === 0) { - var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier])); - return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges(); + }); + // 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. + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); + } + function createStringLiteralWithQuoteStyle(sourceFile, text) { + var literal = ts.createLiteral(text); + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); + return literal; + } + function createImportClauseOfKind(kind, symbolName) { + switch (kind) { + case 1 /* Default */: + return ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined); + case 2 /* Namespace */: + return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))); + case 0 /* Named */: + return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); + default: + ts.Debug.assertNever(kind); + } + } + function getModuleSpecifierForNewImport(sourceFile, moduleSymbol, options, getCanonicalFileName, host) { + var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + return tryGetModuleNameFromAmbientModule(moduleSymbol) || + tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) || + tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) || + tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) || + options.rootDirs && tryGetModuleNameFromRootDirs(options.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName)); + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromBaseUrl(options, moduleFileName, getCanonicalFileName) { + if (!options.baseUrl) { + return undefined; + } + var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl, getCanonicalFileName); + if (!relativeName) { + return undefined; + } + var relativeNameWithIndex = ts.removeFileExtension(relativeName); + 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; } - /** - * If the import list has one import per line, preserve that. Otherwise, insert on same line as last element - * import { - * foo - * } from "./module"; - */ - return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges(); - } - function getCodeActionForNamespaceImport(declaration) { - var namespacePrefix; - if (declaration.kind === 238 /* ImportDeclaration */) { - namespacePrefix = declaration.importClause.namedBindings.name.getText(); + 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 { - namespacePrefix = declaration.name.getText(); + else if (pattern === relativeName || pattern === relativeNameWithIndex) { + return key; } - 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], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange"); } } - function getCodeActionForNewImport(moduleSpecifier) { - if (!lastImportDeclaration) { - // insert after any existing imports - for (var i = sourceFile.statements.length - 1; i >= 0; i--) { - var statement = sourceFile.statements[i]; - if (statement.kind === 237 /* ImportEqualsDeclaration */ || statement.kind === 238 /* ImportDeclaration */) { - lastImportDeclaration = statement; - break; + } + return relativeName; + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + var roots = ts.getEffectiveTypeRoots(options, host); + return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1)); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); - var changeTracker = createChangeTracker(); - var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(symbolName), /*namedBindings*/ undefined) - : isNamespaceImport - ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) - : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); - var moduleSpecifierLiteral = ts.createLiteral(moduleSpecifierWithoutQuotes); - moduleSpecifierLiteral.singleQuote = getSingleQuoteStyleFromExistingImports(); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifierLiteral); - if (!lastImportDeclaration) { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); - } - else { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); - } - // 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. - return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); - function getSingleQuoteStyleFromExistingImports() { - var firstModuleSpecifier = ts.forEach(sourceFile.statements, function (node) { - if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { - if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { - return node.moduleSpecifier; - } - } - else if (ts.isImportEqualsDeclaration(node)) { - if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) { - return node.moduleReference.expression; - } - } - }); - if (firstModuleSpecifier) { - return sourceFile.text.charCodeAt(firstModuleSpecifier.getStart()) === 39 /* singleQuote */; - } - } - function getModuleSpecifierForNewImport() { - var fileName = sourceFile.fileName; - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(fileName); - var options = context.program.getCompilerOptions(); - return tryGetModuleNameFromAmbientModule() || - tryGetModuleNameFromTypeRoots() || - tryGetModuleNameAsNodeModule() || - tryGetModuleNameFromBaseUrl() || - tryGetModuleNameFromRootDirs() || - ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); - function tryGetModuleNameFromAmbientModule() { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromBaseUrl() { - if (!options.baseUrl) { - return undefined; - } - var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl); - if (!relativeName) { - return undefined; - } - var relativeNameWithIndex = ts.removeFileExtension(relativeName); - 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 || pattern === relativeNameWithIndex) { - return key; - } - } - } - } - return relativeName; - } - function tryGetModuleNameFromRootDirs() { - if (options.rootDirs) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs); - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs); - 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); - } - } - } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory, getCanonicalFileName); + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; } - function tryGetModuleNameAsNodeModule() { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (context.host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory); - } - } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDir = rootDirs_1[_i]; - var relativeName = getRelativePathIfInDirectory(path, rootDir); - if (relativeName !== undefined) { - return relativeName; - } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; } - return undefined; - } - function removeExtensionAndIndexPostFix(fileName) { - fileName = ts.removeFileExtension(fileName); - if (ts.endsWith(fileName, "/index")) { - fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + else { + state = 3 /* PackageContent */; } - return fileName; - } - function getRelativePathIfInDirectory(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + } + function removeExtensionAndIndexPostFix(fileName) { + fileName = ts.removeFileExtension(fileName); + if (ts.endsWith(fileName, "/index")) { + fileName = fileName.substr(0, fileName.length - 6 /* "/index".length */); + } + return fileName; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + } + function getRelativePath(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + function getCodeActionForAddImport(moduleSymbol, ctx, declarations) { + var fromExistingImport = ts.firstDefined(declarations, function (declaration) { + if (declaration.kind === 238 /* ImportDeclaration */ && declaration.importClause) { + var changes = tryUpdateExistingImport(ctx, ctx.kind, declaration.importClause); + if (changes) { + var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); + return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes); } - function getRelativePath(path, directoryPath) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; + } + }); + if (fromExistingImport) { + return fromExistingImport; + } + var moduleSpecifier = ts.firstDefined(declarations, moduleSpecifierFromAnyImport) + || getModuleSpecifierForNewImport(ctx.sourceFile, moduleSymbol, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + return getCodeActionForNewImport(ctx, moduleSpecifier); + } + function moduleSpecifierFromAnyImport(node) { + var expression = node.kind === 238 /* ImportDeclaration */ + ? node.moduleSpecifier + : node.moduleReference.kind === 248 /* ExternalModuleReference */ + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? expression.text : undefined; + } + function tryUpdateExistingImport(context, kind, importClause) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + var name = importClause.name, namedBindings = importClause.namedBindings; + switch (kind) { + case 1 /* Default */: + return name ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); + }); + case 0 /* Named */: { + var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); + if (namedBindings && namedBindings.kind === 241 /* NamedImports */ && namedBindings.elements.length !== 0) { + // There are already named imports; add another. + return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); + } + if (!namedBindings || namedBindings.kind === 241 /* NamedImports */ && namedBindings.elements.length === 0) { + return ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); + }); } + return undefined; } + case 2 /* Namespace */: + return namedBindings ? undefined : ChangeTracker.with(context, function (t) { + return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); + }); + default: + ts.Debug.assertNever(kind); + } + } + function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { + var symbolName = context.symbolName, sourceFile = context.sourceFile; + /** + * 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, [symbolName, namespacePrefix + "." + symbolName], ChangeTracker.with(context, function (tracker) { + return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolName)); + }), "CodeChange", + /*moduleSpecifier*/ undefined); + } + function getImportCodeActions(context) { + var importFixContext = convertToImportCodeFixContext(context); + return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getActionsForUMDImport(importFixContext) + : getActionsForNonUMDImport(importFixContext, context.program.getSourceFiles(), context.cancellationToken); + } + function getActionsForUMDImport(context) { + var checker = context.checker, symbolToken = context.symbolToken; + var umdSymbol = checker.getSymbolAtLocation(symbolToken); + var symbol; + var symbolName; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = context.symbolName; } - function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromContext(context); + else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */)); + symbolName = symbol.name; } - function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { - return { - description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), - changes: changes, - kind: kind, - moduleSpecifier: moduleSpecifier - }; + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); } + return getCodeActionForImport(symbol, __assign({}, context, { symbolName: symbolName, kind: 2 /* Namespace */ })); } + function getActionsForNonUMDImport(context, allSourceFiles, cancellationToken) { + var sourceFile = context.sourceFile, checker = context.checker, symbolName = context.symbolName, symbolToken = context.symbolToken; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default"); + var symbolIdActionMap = new ImportCodeActionMap(); + var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol) { + if (moduleSymbol === sourceFile.symbol) { + return; + } + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + if (defaultExport) { + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol && localSymbol.escapedName === symbolName && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + // check if this symbol is already used + var symbolId = ts.getUniqueSymbolId(localSymbol, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); + } + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); + } + }); + return symbolIdActionMap.getAllActions(); + } + function checkSymbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(sourceFile.symbol); + } + } + } + codefix.forEachExternalModule = forEachExternalModule; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91977,7 +92239,7 @@ var ts; if (!usageContext.properties) { usageContext.properties = ts.createUnderscoreEscapedMap(); } - var propertyUsageContext = {}; + var propertyUsageContext = usageContext.properties.get(name) || {}; inferTypeFromContext(parent, checker, propertyUsageContext); usageContext.properties.set(name, propertyUsageContext); } @@ -92028,7 +92290,7 @@ var ts; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker); + symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); members_4.set(name, symbol); }); } @@ -92084,7 +92346,7 @@ var ts; symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); parameters.push(symbol); } - var returnType = getTypeFromUsageContext(callContext.returnType, checker); + var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { @@ -92103,6 +92365,7 @@ var ts; /// /// /// +/// /// /// /// @@ -92118,55 +92381,66 @@ var ts; var ts; (function (ts) { var refactor; - (function (refactor_2) { + (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { var actionName = "annotate"; var annotateTypeFromJSDoc = { name: "Annotate with type from JSDoc", description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAnnotation, - getAvailableActions: getAvailableActions - }; - var annotateFunctionFromJSDoc = { - name: "Annotate with types from JSDoc", - description: ts.Diagnostics.Annotate_with_types_from_JSDoc.message, - getEditsForAction: getEditsForFunctionAnnotation, + getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }; - refactor_2.registerRefactor(annotateTypeFromJSDoc); - refactor_2.registerRefactor(annotateFunctionFromJSDoc); + refactor.registerRefactor(annotateTypeFromJSDoc); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; } var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); - var decl = ts.findAncestor(node, isDeclarationWithType); - if (!decl || decl.type) { - return undefined; - } - var jsdocType = ts.getJSDocType(decl); - var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); - var refactor = (isFunctionWithJSDoc || jsdocType && decl.kind === 146 /* Parameter */) ? annotateFunctionFromJSDoc : - jsdocType ? annotateTypeFromJSDoc : - undefined; - if (refactor) { + if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: refactor.name, - description: refactor.description, + name: annotateTypeFromJSDoc.name, + description: annotateTypeFromJSDoc.description, actions: [ { - description: refactor.description, + description: annotateTypeFromJSDoc.description, name: actionName } ] }]; } } - function getEditsForAnnotation(context, action) { + function hasUsableJSDoc(decl) { + if (!decl) { + return false; + } + if (ts.isFunctionLikeDeclaration(decl)) { + return decl.parameters.some(hasUsableJSDoc) || (!decl.type && !!ts.getJSDocReturnType(decl)); + } + return !decl.type && !!ts.getJSDocType(decl); + } + function getEditsForAction(context, action) { if (actionName !== action) { return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); } + var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, isDeclarationWithType); + if (!decl || decl.type) { + return undefined; + } + var jsdocType = ts.getJSDocType(decl); + var isFunctionWithJSDoc = ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); })); + if (isFunctionWithJSDoc || jsdocType && decl.kind === 146 /* Parameter */) { + return getEditsForFunctionAnnotation(context); + } + else if (jsdocType) { + return getEditsForAnnotation(context); + } + else { + ts.Debug.assert(!!refactor, "No applicable refactor found."); + } + } + function getEditsForAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); var decl = ts.findAncestor(token, isDeclarationWithType); @@ -92184,10 +92458,7 @@ var ts; renameLocation: undefined }; } - function getEditsForFunctionAnnotation(context, action) { - if (actionName !== action) { - return ts.Debug.fail("actionName !== action: " + actionName + " !== " + action); - } + function getEditsForFunctionAnnotation(context) { var sourceFile = context.file; var token = ts.getTokenAtPosition(sourceFile, context.startPosition, /*includeJsDocComment*/ false); var decl = ts.findAncestor(token, ts.isFunctionLikeDeclaration); @@ -92266,7 +92537,9 @@ var ts; case 159 /* TypeReference */: return transformJSDocTypeReference(node); default: - return ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + ts.setEmitFlags(visited, 1 /* SingleLine */); + return visited; } } function transformJSDocOptionalType(node) { @@ -92293,6 +92566,9 @@ var ts; var name = node.typeName; var args = node.typeArguments; if (ts.isIdentifier(node.typeName)) { + if (ts.isJSDocIndexSignature(node)) { + return transformJSDocIndexSignature(node); + } var text = node.typeName.text; switch (node.typeName.text) { case "String": @@ -92317,7 +92593,18 @@ var ts; } return ts.createTypeReferenceNode(name, args); } - })(annotateWithTypeFromJSDoc = refactor_2.annotateWithTypeFromJSDoc || (refactor_2.annotateWithTypeFromJSDoc = {})); + function transformJSDocIndexSignature(node) { + var index = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "n" : "s", + /*questionToken*/ undefined, ts.createTypeReferenceNode(node.typeArguments[0].kind === 133 /* NumberKeyword */ ? "number" : "string", []), + /*initializer*/ undefined); + var indexSignature = ts.createTypeLiteralNode([ts.createIndexSignature(/*decorators*/ undefined, /*modifiers*/ undefined, [index], node.typeArguments[1])]); + ts.setEmitFlags(indexSignature, 1 /* SingleLine */); + return indexSignature; + } + })(annotateWithTypeFromJSDoc = refactor.annotateWithTypeFromJSDoc || (refactor.annotateWithTypeFromJSDoc = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ @@ -92983,27 +93270,26 @@ var ts; : [containingClass]; } } - var start = current; - var scopes = undefined; - while (current) { + var scopes = []; + while (true) { + current = current.parent; + // A function parameter's initializer is actually in the outer scope, not the function declaration + if (current.kind === 146 /* Parameter */) { + // Skip all the way to the outer scope of the function that declared this parameter + current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; + } // We want to find the nearest parent where we can place an "equivalent" sibling to the node we're extracting out of. // Walk up to the closest parent of a place where we can logically put a sibling: // * Function declaration // * Class declaration or expression // * Module/namespace or source file - if (current !== start && isScope(current)) { - (scopes = scopes || []).push(current); - } - // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current && current.parent && current.parent.kind === 146 /* Parameter */) { - // Skip all the way to the outer scope of the function that declared this parameter - current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; - } - else { - current = current.parent; + if (isScope(current)) { + scopes.push(current); + if (current.kind === 265 /* SourceFile */) { + return scopes; + } } } - return scopes; } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; @@ -93070,13 +93356,7 @@ var ts; } function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; - if (targetRange === undefined) { - return undefined; - } var scopes = collectEnclosingScopes(targetRange); - if (scopes === undefined) { - return undefined; - } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); return { scopes: scopes, readsAndWrites: readsAndWrites }; @@ -94113,9 +94393,73 @@ var ts; })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var installTypesForPackage; + (function (installTypesForPackage_1) { + var actionName = "install"; + var installTypesForPackage = { + name: "Install missing types package", + description: "Install missing types package", + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions, + }; + refactor.registerRefactor(installTypesForPackage); + function getAvailableActions(context) { + if (context.program.getCompilerOptions().noImplicitAny) { + // Then it will be available via `fixCannotFindModule`. + return undefined; + } + var action = getAction(context); + return action && [ + { + name: installTypesForPackage.name, + description: installTypesForPackage.description, + actions: [ + { + description: action.description, + name: actionName, + }, + ], + }, + ]; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var action = getAction(context); // Should be defined if we said there was an action available. + return { + edits: [], + renameFilename: undefined, + renameLocation: undefined, + commands: action.commands, + }; + } + function getAction(context) { + var file = context.file, startPosition = context.startPosition; + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + if (ts.isStringLiteral(node) && isModuleIdentifier(node) && ts.getResolvedModule(file, node.text) === undefined) { + return ts.codefix.tryGetCodeActionForInstallPackageTypes(context.host, node.text); + } + } + function isModuleIdentifier(node) { + switch (node.parent.kind) { + case 238 /* ImportDeclaration */: + case 248 /* ExternalModuleReference */: + return true; + default: + return false; + } + } + })(installTypesForPackage = refactor.installTypesForPackage || (refactor.installTypesForPackage = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /// +/// /// /// /// @@ -95016,7 +95360,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -95169,15 +95513,16 @@ var ts; } function getCompletionsAtPosition(fileName, position) { synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position); + return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles()); } - function getCompletionEntryDetails(fileName, position, entryName) { + function getCompletionEntryDetails(fileName, position, entryName, formattingOptions) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + var ruleProvider = formattingOptions ? getRuleProvider(formattingOptions) : undefined; + return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles(), host, ruleProvider); } function getCompletionEntrySymbol(fileName, position, entryName) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName); + return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, entryName, program.getSourceFiles()); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -95326,11 +95671,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles, isDetailed) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, isDetailed, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); } // Signature help /** @@ -95534,6 +95879,17 @@ var ts; return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); } + function applyCodeActionCommand(fileName, action) { + fileName = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + switch (action.type) { + case "install package": + return host.installPackage + ? host.installPackage({ fileName: fileName, packageName: action.packageName }) + : Promise.reject("Host does not implement `installPackage`"); + default: + ts.Debug.fail(); + } + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -95708,8 +96064,9 @@ var ts; endPosition: endPosition, program: getProgram(), newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), + host: host, rulesProvider: getRuleProvider(formatOptions), - cancellationToken: cancellationToken + cancellationToken: cancellationToken, }; } function getApplicableRefactors(fileName, positionOrRange) { @@ -95762,6 +96119,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -96996,9 +97354,12 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions); + }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 44f1e9cd7a355..f0c5cc45ade0c 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -175,8 +175,8 @@ var ts; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; function createDictionaryObject() { var map = Object.create(null); - map["__"] = undefined; - delete map["__"]; + map.__ = undefined; + delete map.__; return map; } function createMap() { @@ -297,6 +297,16 @@ var ts; return undefined; } ts.forEach = forEach; + function firstDefined(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -350,6 +360,16 @@ var ts; return undefined; } ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; function findIndex(array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i], i)) { @@ -1074,6 +1094,15 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey) { + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = value; + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; function arrayToSet(array, makeKey) { return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); } @@ -2274,6 +2303,14 @@ var ts; return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPath(path) { + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -2416,8 +2453,13 @@ var ts; if (parentResult) { var baseName = getBaseNameOfFileName(fileOrDirectory); if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, baseName, host.fileExists(fileOrDirectoryPath)); - updateFileSystemEntry(parentResult.directories, baseName, host.directoryExists(fileOrDirectoryPath)); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + updateFileSystemEntry(parentResult.directories, baseName, fsQueryResult.directoryExists); + return fsQueryResult; } } } @@ -2475,7 +2517,7 @@ var ts; var _path = require("path"); var _os = require("os"); var _crypto = require("crypto"); - var useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"]; + var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; function createWatchedFileSet() { var dirWatchers = ts.createMap(); var fileWatcherCallbacks = ts.createMultiMap(); @@ -2829,7 +2871,7 @@ var ts; } function recursiveCreateDirectory(directoryPath, sys) { var basePath = ts.getDirectoryPath(directoryPath); - var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + var shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath); if (shouldCreateParent) { recursiveCreateDirectory(basePath, sys); } @@ -3784,9 +3826,9 @@ var ts; Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), 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: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "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: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), - Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\"."), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'."), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\"."), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), @@ -4222,6 +4264,16 @@ var ts; } } ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; + function isAnyImportSyntax(node) { + switch (node.kind) { + case 238: + case 237: + return true; + default: + return false; + } + } + ts.isAnyImportSyntax = isAnyImportSyntax; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -4950,6 +5002,14 @@ var ts; return node && !!(node.flags & 1048576); } ts.isInJSDoc = isInJSDoc; + function isJSDocIndexSignature(node) { + return ts.isTypeReferenceNode(node) && + ts.isIdentifier(node.typeName) && + node.typeName.escapedText === "Object" && + node.typeArguments && node.typeArguments.length === 2 && + (node.typeArguments[0].kind === 136 || node.typeArguments[0].kind === 133); + } + ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 181) { return false; @@ -4969,6 +5029,10 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isStringDoubleQuoted(string, sourceFile) { + return getSourceTextOfNodeFromSourceFile(sourceFile, string).charCodeAt(0) === 34; + } + ts.isStringDoubleQuoted = isStringDoubleQuoted; function isDeclarationOfFunctionOrClassExpression(s) { if (s.valueDeclaration && s.valueDeclaration.kind === 226) { var declaration = s.valueDeclaration; @@ -15098,8 +15162,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -15171,8 +15235,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -16344,7 +16408,7 @@ var ts; } } function isDoubleQuotedString(node) { - return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option) { @@ -16539,9 +16603,9 @@ var ts; }; function getFileNames() { var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { - if (ts.isArray(raw["files"])) { - filesSpecs = raw["files"]; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } @@ -16551,25 +16615,25 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { - if (ts.isArray(raw["include"])) { - includeSpecs = raw["include"]; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { - if (ts.isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; + var outDir = raw.compilerOptions && raw.compilerOptions.outDir; if (outDir) { excludeSpecs = [outDir]; } @@ -16639,7 +16703,7 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); var extendedConfigPath; if (json.extends) { @@ -16755,7 +16819,7 @@ var ts; if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { return undefined; } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); if (typeof result === "boolean" && result) { return result; } @@ -17229,6 +17293,50 @@ var ts; } } JsTyping.discoverTypings = discoverTypings; + var MaxPackageNameLength = 214; + function validatePackageName(packageName) { + if (!packageName) { + return 2; + } + if (packageName.length > MaxPackageNameLength) { + return 3; + } + if (packageName.charCodeAt(0) === 46) { + return 4; + } + if (packageName.charCodeAt(0) === 95) { + return 5; + } + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6; + } + return 0; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2: + return "Package name '" + typing + "' cannot be empty"; + case 3: + return "Package name '" + typing + "' should be less than " + MaxPackageNameLength + " characters"; + case 4: + return "Package name '" + typing + "' cannot start with '.'"; + case 5: + return "Package name '" + typing + "' cannot start with '_'"; + case 1: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0: + throw ts.Debug.fail(); + default: + ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); var ts; @@ -17237,6 +17345,8 @@ var ts; (function (server) { server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventPackageInstalled = "event::packageInstalled"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; server.EventInitializationFailed = "event::initializationFailed"; @@ -17957,6 +18067,7 @@ var ts; } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } + ts.getPackageName = getPackageName; function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); } @@ -17999,18 +18110,25 @@ var ts; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; + function mangleScopedPackage(packageName, state) { + var mangled = getMangledNameForScopedPackage(packageName); + if (state.traceEnabled && mangled !== packageName) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + function getTypesPackageName(packageName) { + return "@types/" + getMangledNameForScopedPackage(packageName); + } + ts.getTypesPackageName = getTypesPackageName; + function getMangledNameForScopedPackage(packageName) { + if (ts.startsWith(packageName, "@")) { + var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== packageName) { + return replaceSlash.slice(1); } } - return moduleName; + return packageName; } function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); @@ -18104,39 +18222,6 @@ var ts; return undefined; } } - 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(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) { if (log === void 0) { log = nullLog; } @@ -18283,8 +18368,8 @@ var ts; if (this.missingTypingsSet.get(typing) || this.packageNameToTypingLocation.get(typing)) { continue; } - var validationResult = validatePackageName(typing); - if (validationResult === PackageNameValidationResult.Ok) { + var validationResult = ts.JsTyping.validatePackageName(typing); + if (validationResult === 0) { if (this.typesRegistry.has(typing)) { result.push(typing); } @@ -18297,26 +18382,7 @@ var ts; else { this.missingTypingsSet.set(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; - } + this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing)); } } } @@ -18445,8 +18511,8 @@ var ts; kind: server.ActionSet }; }; - TypingsInstaller.prototype.installTypingsAsync = function (requestId, args, cwd, onRequestCompleted) { - this.pendingRunRequests.unshift({ requestId: requestId, args: args, cwd: cwd, onRequestCompleted: onRequestCompleted }); + TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) { + this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted }); this.executeWithThrottling(); }; TypingsInstaller.prototype.executeWithThrottling = function () { @@ -18454,7 +18520,7 @@ var ts; var _loop_4 = function () { this_1.inFlightRequestCount++; var request = this_1.pendingRunRequests.pop(); - this_1.installWorker(request.requestId, request.args, request.cwd, function (ok) { + this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) { _this.inFlightRequestCount--; request.onRequestCompleted(ok); _this.executeWithThrottling(); @@ -18580,23 +18646,51 @@ var ts; break; case "closeProject": _this.closeProject(req); + break; + case "typesRegistry": { + var typesRegistry_1 = {}; + _this.typesRegistry.forEach(function (value, key) { + typesRegistry_1[key] = value; + }); + var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 }; + _this.sendResponse(response); + break; + } + case "installPackage": { + var fileName = req.fileName, packageName_1 = req.packageName, projectRootPath = req.projectRootPath; + var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath; + if (cwd) { + _this.installWorker(-1, [packageName_1], cwd, function (success) { + var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + "."; + var response = { kind: server.EventPackageInstalled, success: success, message: message }; + _this.sendResponse(response); + }); + } + else { + var response = { kind: server.EventPackageInstalled, success: false, message: "Could not determine a project root path." }; + _this.sendResponse(response); + } + break; + } + default: + ts.Debug.assertNever(req); } }); }; NodeTypingsInstaller.prototype.sendResponse = function (response) { if (this.log.isEnabled()) { - this.log.writeLine("Sending response: " + JSON.stringify(response)); + this.log.writeLine("Sending response:\n " + JSON.stringify(response)); } process.send(response); if (this.log.isEnabled()) { this.log.writeLine("Response has been sent."); } }; - NodeTypingsInstaller.prototype.installWorker = function (requestId, args, cwd, onRequestCompleted) { + NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) { if (this.log.isEnabled()) { - this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(args) + "'."); + this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'."); } - var command = this.npmPath + " install --ignore-scripts " + args.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; + var command = this.npmPath + " install --ignore-scripts " + packageNames.join(" ") + " --save-dev --user-agent=\"typesInstaller/" + ts.version + "\""; var start = Date.now(); var hasError = this.execSyncAndLog(command, { cwd: cwd }); if (this.log.isEnabled()) { @@ -18624,6 +18718,13 @@ var ts; return NodeTypingsInstaller; }(typingsInstaller.TypingsInstaller)); typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller; + function getDirectoryOfPackageJson(fileName, host) { + return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) { + if (host.fileExists(ts.combinePaths(directory, "package.json"))) { + return directory; + } + }); + } var logFilePath = server.findArgument(server.Arguments.LogFile); var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); diff --git a/lib/chs/diagnosticMessages.generated.json b/lib/zh-CN/diagnosticMessages.generated.json similarity index 98% rename from lib/chs/diagnosticMessages.generated.json rename to lib/zh-CN/diagnosticMessages.generated.json index 7afaad352f703..c57371fd9e4fc 100644 --- a/lib/chs/diagnosticMessages.generated.json +++ b/lib/zh-CN/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "只允许在生成器正文中使用 \"yield\" 表达式。", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "无法通过 super 表达式访问“{1}”类中的“{0}”抽象方法。", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象方法只能出现在抽象类中。", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "不能在构造函数中访问类“{1}”中的抽象属性“{0}”。", "Accessibility_modifier_already_seen_1028": "已看到可访问性修饰符。", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "访问器仅在面向 ECMAScript 5 和更高版本时可用。", "Accessors_must_both_be_abstract_or_non_abstract_2676": "两个取值函数必须都是抽象的或都是非抽象的。", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "对象成员无法声明为可选。", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "重载签名无法声明为生成器。", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "乘方表达式的左侧不允许存在具有“{0}”运算符的一元表达式。请考虑用括号将表达式括起。", + "Annotate_with_type_from_JSDoc_95009": "使用 JSDoc 中的类型批注", + "Annotate_with_types_from_JSDoc_95010": "使用 JSDoc 中的类型批注", "Argument_expression_expected_1135": "应为参数表达式。", "Argument_for_0_option_must_be_Colon_1_6046": "“{0}”选项的参数必须为 {1}。", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "类型“{0}”的参数不能赋给类型“{1}”的参数。", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "需要二进制数字。", "Binding_element_0_implicitly_has_an_1_type_7031": "绑定元素“{0}”隐式具有“{1}”类型。", "Block_scoped_variable_0_used_before_its_declaration_2448": "声明之前已使用的块范围变量“{0}”。", + "Call_decorator_expression_90028": "调用修饰器表达式。", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "缺少返回类型批注的调用签名隐式具有返回类型 \"any\"。", "Call_target_does_not_contain_any_signatures_2346": "调用目标不包含任何签名。", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "无法访问“{0}.{1}”,因为“{0}”是类型,不是命名空间。是否要使用“{0}[\"{1}\"]”检索“{0}”中“{1}”属性的类型?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "无法写入文件“{0}”,因为它会覆盖输入文件。", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 子句变量不能有类型批注。", "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 子句变量不能有初始化表达式。", - "Change_0_to_1_90014": "将 {0} 更改为 {1}。", + "Change_0_to_1_90014": "将“{0}”更改为“{1}”。", "Change_extends_to_implements_90003": "将 \"extends\" 更改为 \"implements\"。", "Change_spelling_to_0_90022": "将拼写更改为“{0}”。", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "检查“{0}”是否是“{1}”-“{2}”的最长匹配前缀。", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "类“{0}”错误扩展基类“{1}”。", "Class_0_incorrectly_implements_interface_1_2420": "类“{0}”错误实现接口“{1}”。", "Class_0_used_before_its_declaration_2449": "类“{0}”用于其声明前。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "类声明不能有多个 \"@augments\" 或 \"@extends\" 标记。", "Class_name_cannot_be_0_2414": "类名不能为“{0}”。", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "类静态侧“{0}”错误扩展基类静态侧“{1}”。", "Classes_can_only_extend_a_single_class_1174": "类只能扩展一个类。", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "类型“{0}”中缺少索引签名。", "Index_signatures_are_incompatible_2330": "索引签名不兼容。", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合并声明“{0}”中的单独声明必须全为导出或全为局部声明。", + "Infer_parameter_types_from_usage_95012": "从用法中推断出参数类型。", + "Infer_type_of_0_from_usage_95011": "从用法中推断出“{0}”的类型。", "Initialize_property_0_in_the_constructor_90020": "初始化构造函数中的属性“{0}”。", "Initialize_static_property_0_90021": "初始化静态属性“{0}”。", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "实例成员变量“{0}”的初始化表达式不能引用构造函数中声明的标识符“{1}”。", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "严格模式下“{0}”的使用无效。", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "\"jsxFactory\" 的值无效。“{0}”不是有效的标识符或限定名称。", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "\"--reactNamespace\" 的值无效。“{0}”不是有效的标识符。", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "JSDoc \"@augments {0}\" 与“扩展 {1}”子句不匹配。", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "JSDoc \"@augments\" 未附加到类声明。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" 不匹配 \"extends {2}\" 子句。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" 未附加到类。", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc \"@param\" 标记具有名称 \"{0}\",但不存在具有该名称的参数。", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc \"@typedef\" 标记应具有类型注释,或其后跟有 \"@property\" 或 \"@member\" 标记。", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 类型只能在文档注释内部使用。", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "\"yield*\" 操作数的迭代元素的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "异步生成器中 \"yield\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", "Type_parameter_0_has_a_circular_constraint_2313": "类型参数“{0}”具有循环约束。", + "Type_parameter_0_has_a_circular_default_2716": "类型参数“{0}”具有循环默认值。", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "导出接口中的调用签名的类型参数“{0}”具有或正在使用专用名称“{1}”。", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "导出接口中的构造函数签名的类型参数“{0}”具有或正在使用专用名称“{1}”。", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "导出类的类型参数“{0}”具有或正在使用专用名称“{1}”。", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "监视输入文件。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "不能重命名标准 TypeScript 库中定义的元素。", "You_cannot_rename_this_element_8000": "无法重命名此元素。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "“{0}”收到的参数过少,无法在此处充当修饰器。你是要先调用它,然后再写入 \"@{0}()\" 吗?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "“{0}”被指定了两次。将覆盖名为“{0}”的特性。", "_0_can_only_be_used_in_a_ts_file_8009": "“{0}”只能在 .ts 文件中使用。", "_0_expected_1005": "应为“{0}”。", diff --git a/lib/cht/diagnosticMessages.generated.json b/lib/zh-TW/diagnosticMessages.generated.json similarity index 99% rename from lib/cht/diagnosticMessages.generated.json rename to lib/zh-TW/diagnosticMessages.generated.json index b5dacb3b2a9b8..4d77c7cf67b9e 100644 --- a/lib/cht/diagnosticMessages.generated.json +++ b/lib/zh-TW/diagnosticMessages.generated.json @@ -83,6 +83,7 @@ "A_yield_expression_is_only_allowed_in_a_generator_body_1163": "只有產生器主體才允許 'yield' 運算式。", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "無法透過 super 運算式存取類別 '{1}' 中的抽象方法 '{0}'。", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象方法只可出現在抽象類別中。", + "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "無法從建構函式存取類別 '{1}' 中的抽象屬性 '{0}'。", "Accessibility_modifier_already_seen_1028": "已有存取範圍修飾詞。", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "只有當目標為 ECMAScript 5 及更高版本時,才可使用存取子。", "Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。", @@ -142,6 +143,8 @@ "An_object_member_cannot_be_declared_optional_1162": "不得將物件成員宣告為選擇性。", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "不可將多載簽章宣告為產生器。", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "乘冪運算式左邊不允許具 '{0}' 運算子的一元運算式。請考慮以括弧括住運算式。", + "Annotate_with_type_from_JSDoc_95009": "為來自 JSDoc 的類型標註", + "Annotate_with_types_from_JSDoc_95010": "為來自 JSDoc 的類型標註", "Argument_expression_expected_1135": "必須是引數運算式。", "Argument_for_0_option_must_be_Colon_1_6046": "'{0}' 選項的引數必須是: {1}。", "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345": "類型 '{0}' 的引數不可指派給類型 '{1}' 的參數。", @@ -158,6 +161,7 @@ "Binary_digit_expected_1177": "必須是二進位數字。", "Binding_element_0_implicitly_has_an_1_type_7031": "繫結元素 '{0}' 隱含擁有 '{1}' 類型。", "Block_scoped_variable_0_used_before_its_declaration_2448": "已在其宣告之前使用區塊範圍變數 '{0}'。", + "Call_decorator_expression_90028": "呼叫裝飾項目運算式。", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "缺少傳回型別註解的呼叫簽章隱含了 'any' 傳回型別。", "Call_target_does_not_contain_any_signatures_2346": "呼叫目標未包含任何特徵標記。", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "因為 '{0}' 是類型而非命名空間,所以無法存取 '{0}.{1}'。您要在 '{0}' 中使用 '{0}[\"{1}\"]' 擷取屬性 '{1}' 的類型嗎?", @@ -202,7 +206,7 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "無法寫入檔案 '{0}',原因是其會覆寫輸入檔。", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch 子句變數不得有類型註釋。", "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch 子句變數不得有初始設定式。", - "Change_0_to_1_90014": "將 {0} 變更為 {1}。", + "Change_0_to_1_90014": "將 '{0}' 變更為 '{1}'。", "Change_extends_to_implements_90003": "將 'extends' 變更為 'implements'。", "Change_spelling_to_0_90022": "將拼字變更為 '{0}'。", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "檢查 '{0}' 是否為 '{1}' - '{2}' 的最長相符前置詞。", @@ -215,6 +219,7 @@ "Class_0_incorrectly_extends_base_class_1_2415": "類別 '{0}' 不正確地擴充基底類別 '{1}'。", "Class_0_incorrectly_implements_interface_1_2420": "類別 '{0}' 不正確地實作介面 '{1}'。", "Class_0_used_before_its_declaration_2449": "類別 '{0}' 的位置在其宣告之前。", + "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "類別宣告只可有一個 '@augments' 或 '@extends' 標記。", "Class_name_cannot_be_0_2414": "類別名稱不得為 '{0}'。", "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417": "類別靜態端 '{0}' 不正確地擴充基底類別靜態端 '{1}'。", "Classes_can_only_extend_a_single_class_1174": "類別只能擴充一個類別。", @@ -409,6 +414,8 @@ "Index_signature_is_missing_in_type_0_2329": "類型 '{0}' 中遺漏索引簽章。", "Index_signatures_are_incompatible_2330": "索引簽章不相容。", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合併宣告 '{0}' 中的個別宣告必須全部匯出或全在本機上。", + "Infer_parameter_types_from_usage_95012": "從用法推斷參數類型。", + "Infer_type_of_0_from_usage_95011": "從用法推斷 '{0}' 的類型。", "Initialize_property_0_in_the_constructor_90020": "初始化建構函式中的屬性 '{0}'。", "Initialize_static_property_0_90021": "初始化靜態屬性 '{0}'。", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "執行個體成員變數 '{0}' 的初始設定式不得參考建構函式中所宣告的識別碼 '{1}'。", @@ -430,8 +437,8 @@ "Invalid_use_of_0_in_strict_mode_1100": "在 strict 模式中使用 '{0}' 無效。", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' 的值無效。'{0}' 不是有效的識別碼或限定名稱。", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' 的值無效。'{0}' 不是有效的識別碼。", - "JSDoc_augments_0_does_not_match_the_extends_1_clause_8023": "JSDoc '@augments {0}' 不符合 'extends {1}' 子句。", - "JSDoc_augments_is_not_attached_to_a_class_declaration_8022": "JSDoc '@augments' 未連結至類別宣告。", + "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' 不符合 'extends {2}' 子句。", + "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc ''@{0}' 未連結到類別。", "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "JSDoc '@param' 標記的名稱為 '{0}',但沒有為該名稱的參數。", "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 標記應具有類型註解,或者其後接著 '@property' 或 '@member' 標記。", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 類型只能在文件註解中使用。", @@ -785,6 +792,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' 運算元的反覆項目類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同步產生器中的 'yield' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", "Type_parameter_0_has_a_circular_constraint_2313": "類型參數 '{0}' 具有循環條件約束。", + "Type_parameter_0_has_a_circular_default_2716": "型別參數 '{0}' 包含循環的預設值。", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "匯出介面中呼叫簽章的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "匯出介面中建構函式簽章的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "匯出類別的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", @@ -838,6 +846,7 @@ "Watch_input_files_6005": "監看輸入檔案。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "您無法重新命名標準 TypeScript 程式庫中所定義的項目。", "You_cannot_rename_this_element_8000": "您無法重新命名這個項目。", + "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' 在此只接受極少數的引數用為裝飾項目。要先呼叫此項目,然後再寫入 '@{0}()' 嗎?", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' 指定了兩次。將會覆寫名為 '{0}' 的屬性。", "_0_can_only_be_used_in_a_ts_file_8009": "'{0}' 只可用於 .ts 檔案中。", "_0_expected_1005": "必須是 '{0}'。", diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts index c2ac33c83fc19..899ab700bf372 100644 --- a/scripts/buildProtocol.ts +++ b/scripts/buildProtocol.ts @@ -51,22 +51,25 @@ class DeclarationsWalker { 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 && !isStringEnum(decl as ts.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 + const declarations = s.getDeclarations(); + if (declarations) { + for (const decl of declarations) { + const sourceFile = decl.getSourceFile(); + if (sourceFile === this.protocolFile || path.basename(sourceFile.fileName) === "lib.d.ts") { + return; + } + if (decl.kind === ts.SyntaxKind.EnumDeclaration && !isStringEnum(decl as ts.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); + this.visitTypeNodes(decl); + } } } } diff --git a/scripts/generateLocalizedDiagnosticMessages.ts b/scripts/generateLocalizedDiagnosticMessages.ts index edfe957515516..36df92590c7e9 100644 --- a/scripts/generateLocalizedDiagnosticMessages.ts +++ b/scripts/generateLocalizedDiagnosticMessages.ts @@ -27,16 +27,54 @@ function main(): void { function visitDirectory(name: string) { const inputFilePath = path.join(inputPath, name, "diagnosticMessages", "diagnosticMessages.generated.json.lcl"); - const outputFilePath = path.join(outputPath, name, "diagnosticMessages.generated.json"); + fs.readFile(inputFilePath, (err, data) => { handleError(err); xml2js.parseString(data.toString(), (err, result) => { handleError(err); - writeFile(outputFilePath, xmlObjectToString(result)); + if (!result || !result.LCX || !result.LCX.$ || !result.LCX.$.TgtCul) { + console.error("Unexpected XML file structure. Expected to find result.LCX.$.TgtCul."); + process.exit(1); + } + const outputDirectoryName = getPreferedLocaleName(result.LCX.$.TgtCul); + if (!outputDirectoryName) { + console.error(`Invalid output locale name for '${result.LCX.$.TgtCul}'.`); + process.exit(1); + } + writeFile(path.join(outputPath, outputDirectoryName, "diagnosticMessages.generated.json"), xmlObjectToString(result)); }); }); } + /** + * A locale name is based on the language tagging conventions of RFC 4646 (Windows Vista + * and later), and is represented by LOCALE_SNAME. + * Generally, the pattern - is used. Here, language is a lowercase ISO 639 + * language code. The codes from ISO 639-1 are used when available. Otherwise, codes from + * ISO 639-2/T are used. REGION specifies an uppercase ISO 3166-1 country/region identifier. + * For example, the locale name for English (United States) is "en-US" and the locale name + * for Divehi (Maldives) is "dv-MV". + * + * If the locale is a neutral locale (no region), the LOCALE_SNAME value follows the + * pattern . If it is a neutral locale for which the script is significant, the + * pattern is -