diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 8326f8fc73983..1ce1f3ab21e57 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -12,11 +12,11 @@ "A_class_member_cannot_have_the_0_keyword_1248": "Člen třídy nemůže mít klíčové slovo {0}.", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Výraz s čárkou není v názvu počítané vlastnosti povolený.", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Název počítané vlastnosti nemůže odkazovat na parametr typu z jeho nadřazeného typu.", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Název vypočítané vlastnosti v deklaraci vlastnosti třídy musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Název vypočítané vlastnosti v přetížené metodě musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Název vypočítané vlastnosti v literálu typu musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Název vypočítané vlastnosti v ambientním kontextu musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Název vypočítané vlastnosti v rozhraní musí odkazovat na výraz, jehož typ je literál nebo jedinečný symbol.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Název počítané vlastnosti v deklaraci vlastnosti třídy musí přímo odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Název počítané vlastnosti v přetížené metodě musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Název počítané vlastnosti v literálu typu musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Název počítané vlastnosti v ambientním kontextu musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Název počítané vlastnosti v rozhraní musí odkazovat na výraz, jehož typ je literál nebo unique symbol.", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Název počítané vlastnosti musí být typu string, number, symbol nebo any.", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Název počítané vlastnosti ve formátu {0} musí být typu symbol.", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Ke členu konstantního výčtu se dá získat přístup jenom pomocí řetězcového literálu.", @@ -48,14 +48,15 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklarace oboru názvů nemůže být v jiném souboru než třída nebo funkce, se kterou se slučuje.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklarace oboru názvů nemůže být umístěná před třídou nebo funkcí, se kterou se slučuje.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklarace oboru názvů je povolená jenom v oboru názvů nebo v modulu.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Import stylu oboru názvů není možné vyvolat nebo konstruovat a způsobí selhání za běhu.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicializátor parametru je povolený jenom v implementaci funkce nebo konstruktoru.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Vlastnost parametru se nedá deklarovat pomocí parametru rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Vlastnost parametru je povolená jenom v implementaci konstruktoru.", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Vlastnost parametru se nedá deklarovat pomocí vzoru vazby.", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Cesta v možnosti extends musí být relativní nebo mít kořen, ale {0} nic z toho nesplňuje.", "A_promise_must_have_a_then_method_1059": "Příslib musí mít metodu then.", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Vlastnost třídy, jejíž typ je jedinečný symbol, musí být static a readonly.", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Vlastnost rozhraní nebo literálu typu, jehož typ je jedinečný symbol, musí být readonly.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Vlastnost třídy, jejíž typ je unique symbol, musí být static a readonly.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Vlastnost rozhraní nebo literálu typu, jehož typ je unique symbol, musí být readonly.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Povinný parametr nemůže následovat po nepovinném parametru.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Element rest nemůže obsahovat vzor vazby.", "A_rest_element_cannot_have_an_initializer_1186": "Element rest nemůže obsahovat inicializátor.", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Predikát typu nemůže odkazovat na element {0} ve vzoru vazby.", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Predikát typu je povolený jenom na pozici návratového typu funkcí a metod.", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Typ predikátu typu musí být přiřaditelný k typu jeho parametru.", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Proměnná, jejíž typ je jedinečný symbol, musí být const.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Proměnná, jejíž typ je unique symbol, musí být const.", "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ě.", @@ -91,11 +92,12 @@ "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í.", - "Add_0_to_existing_import_declaration_from_1_90015": "Přidá {0} k existující deklaraci importu z {1}.", + "Add_0_to_existing_import_declaration_from_1_90015": "Přidat {0} k existující deklaraci importu z {1}", + "Add_async_modifier_to_containing_function_90029": "Přidat modifikátor async do obsahující funkce", "Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}", - "Add_missing_super_call_90001": "Přidejte chybějící volání metody super().", - "Add_this_to_unresolved_variable_90008": "Přidejte k nerozpoznané proměnné this.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Přidání souboru tsconfig.json vám pomůže uspořádat projekty, které obsahují jak soubory TypeScript, tak soubory JavaScript. Další informace najdete na adrese https://aka.ms/tsconfig.", + "Add_missing_super_call_90001": "Přidat chybějící volání metody super()", + "Add_this_to_unresolved_variable_90008": "Přidat k nerozpoznané proměnné this.", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Přidání souboru tsconfig.json vám pomůže uspořádat projekty, které obsahují jak soubory TypeScript, tak soubory JavaScript. Další informace najdete na adrese https://aka.ms/tsconfig.", "Additional_Checks_6176": "Další kontroly", "Advanced_Options_6178": "Upřesnit možnosti", "All_declarations_of_0_must_have_identical_modifiers_2687": "Všechny deklarace {0} musí mít stejné modifikátory.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "V parametru signatury indexu nemůže být modifikátor přístupnosti.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "V parametru signatury indexu nemůže být inicializátor.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "V parametru signatury indexu nemůže být anotace typu.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Typ parametru signatury indexu nemůže být alias typu. Místo toho zvažte toto zadání: [{0}: {1}]: {2}.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Typ parametru signatury indexu nemůže být typ sjednocení. Místo toho zvažte použití namapovaného typu objektu.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr signatury indexu musí být typu string nebo number.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Rozhraní může rozšířit jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Rozhraní může rozšiřovat jenom třídu nebo jiné rozhraní.", @@ -165,7 +169,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_decorator_expression_90028": "Zavolat výraz dekorátoru", "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}]?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Soubory deklarací typů nejde importovat. Zvažte možnost místo {1} naimportovat {0}.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Proměnnou {0} s vnějším oborem nejde inicializovat ve stejném oboru jako deklaraci {1} s oborem bloku.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nejde vyvolat výraz, v jehož typu chybí signatura volání. Typ {0} nemá žádné kompatibilní signatury volání.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nejde vyvolat objekt, který může být null.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nejde vyvolat objekt, který může být null nebo nedefinovaný.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nejde vyvolat objekt, který může být nedefinovaný.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Typ nejde znovu exportovat, pokud je zadaný příznak --isolatedModules.", "Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}", "Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.", @@ -211,7 +218,7 @@ "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Proměnná klauzule catch nemůže mít anotaci typu.", "Catch_clause_variable_cannot_have_an_initializer_1197": "Proměnná klauzule catch nemůže mít inicializátor.", "Change_0_to_1_90014": "Změnit {0} na {1}", - "Change_extends_to_implements_90003": "Změňte extends na implements.", + "Change_extends_to_implements_90003": "Změnit extends na implements", "Change_spelling_to_0_90022": "Změnit pravopis na {0}", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Kontroluje se, jestli je {0} nejdelší odpovídající předpona pro {1}–{2}.", "Circular_definition_of_import_alias_0_2303": "Cyklická definice aliasu importu {0}", @@ -221,9 +228,10 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Třída {0} definuje členskou funkci instance {1}, ale rozšířená třída {2} ji definuje jako vlastnost člena instance.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Třída {0} definuje vlastnost člena instance {1}, ale rozšířená třída {2} ji definuje jako členskou funkci instance.", "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_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Třída {0} nesprávně implementuje třídu {1}. Nechtěli jste rozšířit třídu {1} a dědit její členy jako podtřídu?", "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_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Deklarace tříd nemůžou mít 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.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Není zadaný obsažený soubor a nedá se určit kořenový adresář – přeskakuje se vyhledávání ve složce node_modules.", "Convert_function_0_to_class_95002": "Převést funkci {0} na třídu", "Convert_function_to_an_ES2015_class_95001": "Převést funkci na třídu ES2015", + "Convert_to_ES6_module_95017": "Převést na modul ES6", "Convert_to_default_import_95013": "Převést na výchozí import", "Corrupted_locale_file_0_6051": "Soubor národního prostředí {0} je poškozený.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nenašel se soubor deklarací pro modul {0}. {1} má implicitně typ any.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Očekává se deklarace.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Název deklarace je v konfliktu s integrovaným globálním identifikátorem {0}.", "Declaration_or_statement_expected_1128": "Očekává se deklarace nebo příkaz.", - "Declare_method_0_90023": "Deklarujte metodu {0}.", - "Declare_property_0_90016": "Deklarujte vlastnost {0}.", - "Declare_static_method_0_90024": "Deklarujte statickou metodu {0}.", - "Declare_static_property_0_90027": "Deklarujte statickou vlastnost {0}.", + "Declare_method_0_90023": "Deklarovat metodu {0}", + "Declare_property_0_90016": "Deklarovat vlastnost {0}", + "Declare_static_method_0_90024": "Deklarovat statickou metodu {0}", + "Declare_static_property_0_90027": "Deklarovat statickou vlastnost {0}", "Decorators_are_not_valid_here_1206": "Dekorátory tady nejsou platné.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekorátory nejde použít na víc přístupových objektů get/set se stejným názvem.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Výchozí export modulu má nebo používá privátní název {0}.", @@ -305,10 +314,11 @@ "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Vygeneruje jediný soubor se zdrojovými mapováními namísto samostatného souboru.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Vygeneruje zdroj spolu se zdrojovými mapováními v jednom souboru. Vyžaduje, aby byla nastavená možnost --inlineSourceMap nebo --sourceMap.", "Enable_all_strict_type_checking_options_6180": "Povolí všechny možnosti striktní kontroly typů.", - "Enable_strict_checking_of_function_types_6186": "Povolte striktní kontrolu typů funkcí.", + "Enable_strict_checking_of_function_types_6186": "Povolí striktní kontrolu typů funkcí.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Povolí striktní kontrolu inicializace vlastností ve třídách.", "Enable_strict_null_checks_6113": "Povolte striktní kontroly hodnot null.", "Enable_tracing_of_the_name_resolution_process_6085": "Povolte trasování procesu překladu IP adres.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Povolí interoperabilitu generování mezi moduly CommonJS a ES prostřednictvím vytváření objektů oboru názvů pro všechny importy. Implikuje allowSyntheticDefaultImports.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zapíná experimentální podporu asynchronních funkcí ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Povolí experimentální podporu pro dekorátory ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Povolí experimentální podporu pro generování metadat typu pro dekorátory.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Název souboru {0} se od už zahrnutého názvu souboru {1} liší jenom velikostí písmen.", "File_name_0_has_a_1_extension_stripping_it_6132": "Název souboru {0} má příponu {1} – odstraňuje se", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Specifikace souboru nemůže obsahovat nadřazený adresář (..), který se vyskytuje za rekurzivním zástupným znakem adresáře (**): {0}.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Specifikace souboru nemůže obsahovat víc než jeden rekurzivní zástupný znak adresáře (**): {0}.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Specifikace souboru nemůže končit rekurzivním zástupným znakem adresáře (**): {0}.", "Found_package_json_at_0_6099": "Soubor package.json se našel v {0}.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Deklarace funkcí nejsou povolené uvnitř bloků ve striktním režimu, pokud je cíl ES3 nebo ES5.", @@ -405,10 +414,10 @@ "Identifier_expected_1003": "Očekával se identifikátor.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Očekává se identifikátor. __esModule je při transformaci modulů ECMAScript rezervované jako označení exportu.", "Ignore_this_error_message_90019": "Ignorovat tuto chybovou zprávu", - "Implement_inherited_abstract_class_90007": "Implementujte zděděnou abstraktní třídu.", - "Implement_interface_0_90006": "Implementujte rozhraní {0}.", + "Implement_inherited_abstract_class_90007": "Implementovat zděděnou abstraktní třídu", + "Implement_interface_0_90006": "Implementovat rozhraní {0}", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Klauzule implements exportované třídy {0} má nebo používá privátní název {1}.", - "Import_0_from_module_1_90013": "Import {0} z modulu {1}", + "Import_0_from_module_1_90013": "Importovat {0} z modulu {1}", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Přiřazení importu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít import * as ns from \"mod\", import {a} from \"mod\", import d from \"mod\" nebo jiný formát modulu.", "Import_declaration_0_is_using_private_name_1_4000": "Deklarace importu {0} používá privátní název {1}.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklarace importu je v konfliktu s místní deklarací {0}.", @@ -424,8 +433,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í", + "Infer_parameter_types_from_usage_95012": "Odvodit typy parametrů z využití", + "Infer_type_of_0_from_usage_95011": "Odvodit typ {0} z využití", "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.", @@ -451,8 +460,8 @@ "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_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc ... se může nacházet jen v posledním parametru signatury.", - "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_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024": "Značka JSDoc @param má název {0}, ale neexistuje žádný parametr s tímto názvem.", + "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 poznámku k typu nebo by za ní měly následovat značky @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.", "JSX_attribute_expected_17003": "Očekával se atribut JSX.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atributy JSX musí mít přiřazený neprázdný výraz.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "Nejdelší odpovídající předpona pro {0} je {1}.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Hledání ve složce node_modules, počáteční umístění {0}", "Make_super_call_the_first_statement_in_the_constructor_90002": "Nastavit volání metody super() jako první příkaz v konstruktoru", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Typu mapovaného objektu má implicitně typ šablony any.", "Member_0_implicitly_has_an_1_type_7008": "Člen {0} má implicitně typ {1}.", "Merge_conflict_marker_encountered_1185": "Zjistila se značka konfliktu sloučení.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Spojená deklarace {0} nemůže obsahovat výchozí deklaraci exportu. Zvažte namísto toho možnost přidat samostatnou deklaraci export default {0}.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Název modulu {0} byl úspěšně přeložen na {1}. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Druh překladu modulu nebyl určen, použije se {0}.", "Module_resolution_using_rootDirs_has_failed_6111": "Překlad modulu pomocí rootDirs se nepovedl.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Více po sobě jdoucích číselných oddělovačů se nepovoluje.", "Multiple_constructor_implementations_are_not_allowed_2392": "Víc implementací konstruktoru se nepovoluje.", "NEWLINE_6061": "NOVÝ ŘÁDEK", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Pojmenovaná vlastnost {0} není u typu {1} stejná jako u typu {2}.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Výraz neabstraktní třídy neimplementuje zděděný abstraktní člen {0} z třídy {1}.", "Not_all_code_paths_return_a_value_7030": "Ne všechny cesty kódu vracejí hodnotu.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Typ číselného indexu {0} se nedá přiřadit k typu indexu řetězce {1}.", + "Numeric_separators_are_not_allowed_here_6188": "Číselné oddělovače tady nejsou povolené.", "Object_is_possibly_null_2531": "Objekt je pravděpodobně null.", "Object_is_possibly_null_or_undefined_2533": "Objekt je pravděpodobně null nebo undefined.", "Object_is_possibly_undefined_2532": "Objekt je pravděpodobně undefined.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Vlastnost {0} nemá žádný inicializátor a není jednoznačně přiřazena v konstruktoru.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt get nemá anotaci návratového typu.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt set nemá anotaci parametrového typu.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Vlastnost {0} v typu {1} nejde přiřadit ke stejné vlastnosti v základním typu {2}.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Vlastnost {0} v typu {1} nejde přiřadit typu {2}.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Deklaruje se vlastnost {0}, ale její hodnota se vůbec nečte.", "Property_0_is_incompatible_with_index_signature_2530": "Vlastnost {0} není kompatibilní se signaturou indexu.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Vyvolat chybu u výrazů a deklarací s implikovaným typem any", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Vyvolá chybu u výrazů this s implikovaným typem any.", "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", - "Remove_declaration_for_Colon_0_90004": "Odeberte deklaraci pro {0}.", + "Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}", + "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Oznámí se chyba, když některé cesty kódu ve funkci nevracejí hodnotu.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Oznámí se chyby v případech fallthrough v příkazu switch.", "Report_errors_in_js_files_8019": "Ohlásit chyby v souborech .js", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Návratový typ veřejné statické metody z exportované třídy má nebo používá privátní název {0}.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Znovu se používají vyhodnocení modulu z {0}, protože vyhodnocení se oproti původnímu programu nezměnila.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Znovu se používá vyhodnocení modulu {0} do souboru {1} z původního programu.", - "Rewrite_as_the_indexed_access_type_0_90026": "Proveďte přepis jako indexovaný přístupový typ {0}.", + "Rewrite_as_the_indexed_access_type_0_90026": "Přepsat jako indexovaný typ přístupu {0}", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Nedá se určit kořenový adresář, přeskakují se primární cesty hledání.", "STRATEGY_6039": "STRATEGIE", "Scoped_package_detected_looking_in_0_6182": "Zjištěn balíček v oboru, hledání v: {0}", @@ -688,12 +702,12 @@ "Show_all_compiler_options_6169": "Zobrazí všechny možnosti kompilátoru.", "Show_diagnostic_information_6149": "Zobrazí diagnostické informace.", "Show_verbose_diagnostic_information_6150": "Zobrazí podrobné diagnostické informace.", - "Signature_0_must_be_a_type_predicate_1224": "Podpis {0} musí být predikát typu.", + "Signature_0_must_be_a_type_predicate_1224": "Signatura {0} musí být predikát typu.", "Skip_type_checking_of_declaration_files_6012": "Přeskočit kontrolu typu souborů deklarace", "Source_Map_Options_6175": "Možnosti zdrojového mapování", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Specializovaná signatura přetížení nejde přiřadit žádnému nespecializovanému podpisu.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Specifikátor dynamického importu nemůže být elementem Spread.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Zadejte cílovou verzi ECMAScriptu: ES3 (výchozí), ES5, ES2015, ES2016, ES2017, nebo ESNEXT.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Zadejte cílovou verzi ECMAScriptu: ES3 (výchozí), ES5, ES2015, ES2016, ES2017, ES2018 nebo ESNEXT.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Zadejte generování kódu JSX: preserve, react-native, nebo react.", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Zadejte soubory knihovny, které se mají zahrnout do kompilace: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Určete generování kódu modulu: none, commonjs, amd, system, umd, es2015 nebo ESNext.", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Zadejte kořenový adresář vstupních souborů. Slouží ke kontrole struktury výstupního adresáře pomocí --outDir.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Operátor rozšíření ve výrazech new je dostupný jenom při cílení na verzi ECMAScript 5 a vyšší.", "Spread_types_may_only_be_created_from_object_types_2698": "Typy spread se dají vytvářet jenom z typů object.", + "Starting_compilation_in_watch_mode_6031": "Spouští se kompilace v režimu sledování...", "Statement_expected_1129": "Očekává se příkaz.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Příkazy se nepovolují v ambientních kontextech.", "Static_members_cannot_reference_class_type_parameters_2302": "Statické členy nemůžou odkazovat na parametry typu třídy.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Očekává se řetězcový literál.", "String_literal_with_double_quotes_expected_1327": "Očekával se řetězcový literál s dvojitými uvozovkami.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylizujte chyby a zprávy pomocí barev a kontextu (experimentální).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Deklarace následných vlastností musí obsahovat stejný typ. Vlastnost {0} musí být typu {1}, ale tady je typu {2}.", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Deklarace následných proměnných musí obsahovat stejný typ. Proměnná {0} musí být typu {1}, ale tady je typu {2}.", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Nahrazení {0} za vzor {1} má nesprávný typ, očekával se typ string, obdržený je {2}.", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Nahrazení {0} ve vzoru {1} může obsahovat nanejvýš jeden znak * (hvězdička).", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ {0} není typem pole nebo řetězce, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ {0} není typem pole, nebo nemá metodu [Symbol.iterator](), která vrací iterátor.", "Type_0_is_not_assignable_to_type_1_2322": "Typ {0} nejde přiřadit typu {1}.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Typ {0} se nedá přiřadit typu {1}. Existují dva různé typy s tímto názvem, ale nesouvisí spolu.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Typ {0} se nedá přiřadit typu {1}. Existují dva různé typy s tímto názvem, ale nesouvisí spolu.", "Type_0_is_not_comparable_to_type_1_2678": "Typ {0} se nedá porovnat s typem {1}.", "Type_0_is_not_generic_2315": "Typ {0} není obecný.", "Type_0_provides_no_match_for_the_signature_1_2658": "Typ {0} neposkytuje žádnou shodu pro podpis {1}.", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Neukončený literál šablony", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Volání netypové funkce nemusí přijmout argumenty typu.", "Unused_label_7028": "Nepoužívaný popisek", + "Use_synthetic_default_member_95016": "Použije syntetického výchozího člena.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", "VERSION_6036": "VERZE", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Hodnota typu {0} nemá žádné vlastnosti společné s typem {1}. Chtěli jste ji volat?", @@ -913,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Deklarace const se musejí inicializovat.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Inicializátor člena výčtu const se vyhodnotil na nekonečnou hodnotu.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Inicializátor člena výčtu const se vyhodnotil na nepovolenou hodnotu NaN.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Výčty const se dají použít jenom ve výrazech přístupu k vlastnosti nebo indexu nebo na pravé straně deklarace importu nebo přiřazení exportu.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Výčty const se dají použít jenom ve výrazech přístupu k vlastnosti nebo indexu nebo na pravé straně deklarace importu, přiřazení exportu nebo dotazu na typ.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Příkaz delete nejde volat u identifikátoru ve striktním režimu.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklarace výčtu se dají použít jenom v souboru .ts.", "export_can_only_be_used_in_a_ts_file_8003": "Možnost export= se dá použít jenom v souboru .ts.", @@ -937,7 +953,7 @@ "non_null_assertions_can_only_be_used_in_a_ts_file_8013": "Kontrolní výrazy nenabývající hodnoty null lze použít jen v souboru .ts.", "options_6024": "možnosti", "or_expected_1144": "Očekává se znak { nebo ;.", - "package_json_does_not_have_a_0_field_6100": "package.json nemá pole {0}.", + "package_json_does_not_have_a_0_field_6100": "Soubor package.json neobsahuje pole {0}.", "package_json_has_0_field_1_that_references_2_6101": "Soubor package.json má pole {0} {1}, které odkazuje na {2}.", "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "Modifikátory parametrů se dají použít jenom v souboru .ts.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "Je zadaná možnost paths, hledá se vzor, který odpovídá názvu modulu {0}.", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Výrazy potvrzení typu se dají použít jenom v souboru .ts.", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Deklarace parametru typu se dají použít jenom v souboru .ts.", "types_can_only_be_used_in_a_ts_file_8010": "Typy se dají použít jenom v souboru .ts.", - "unique_symbol_types_are_not_allowed_here_1335": "Typy „jedinečný symbol“ tady nejsou povolené.", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy „jedinečný symbol“ jsou povolené jen u proměnných v příkazu proměnné.", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typy „jedinečný symbol“ nejde použít v deklaraci proměnné s názvem vazby.", + "unique_symbol_types_are_not_allowed_here_1335": "Typy unique symbol tady nejsou povolené.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy unique symbol jsou povolené jen u proměnných v příkazu proměnné.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typy unique symbol nejde použít v deklaraci proměnné s názvem vazby.", "with_statements_are_not_allowed_in_an_async_function_block_1300": "Příkazy with se ve funkčním bloku async nepovolují.", "with_statements_are_not_allowed_in_strict_mode_1101": "Příkazy with se ve striktním režimu nepovolují.", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Výrazy yield nejde použít v inicializátoru parametru." diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 96aa622274420..18dbf7c9f2217 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Eine Namespacedeklaration darf sich nicht in einer anderen Datei als die Klasse oder Funktion befinden, mit der sie zusammengeführt wird.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Eine Namespacedeklaration darf nicht vor der Klasse oder Funktion positioniert werden, mit der sie zusammengeführt wird.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Eine Namespacedeklaration ist nur in einem Namespace oder Modul zulässig.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Ein Import im Namespacestil kann nicht aufgerufen oder erstellt werden und verursacht zur Laufzeit einen Fehler.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Ein Parameterinitialisierer ist nur in einer Funktions- oder Konstruktorimplementierung zulässig.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Eine Parametereigenschaft darf nicht mithilfe eines rest-Parameters deklariert werden.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Eine Parametereigenschaft ist nur in einer Konstruktorimplementierung zulässig.", @@ -91,11 +92,12 @@ "Accessibility_modifier_already_seen_1028": "Der Zugriffsmodifizierer ist bereits vorhanden.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Zugriffsmethoden sind nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.", - "Add_0_to_existing_import_declaration_from_1_90015": "Fügen Sie \"{0}\" zur vorhandenen Importdeklaration aus \"{1}\" hinzu.", - "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen.", - "Add_missing_super_call_90001": "Fügen Sie den fehlenden super()-Aufruf hinzu.", - "Add_this_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"this.\" hinzufügen.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Das Hinzufügen einer \"tsconfig.json\"-Datei erleichtert die Organisation von Projekten, die sowohl TypeScript- als auch JavaScript-Dateien enthalten. Weitere Informationen finden Sie unter https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "\"{0}\" der vorhandenen Importdeklaration aus \"{1}\" hinzufügen", + "Add_async_modifier_to_containing_function_90029": "Async-Modifizierer zur enthaltenden Funktion hinzufügen", + "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen", + "Add_missing_super_call_90001": "Fehlenden super()-Aufruf hinzufügen", + "Add_this_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"this.\" hinzufügen", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Das Hinzufügen einer \"tsconfig.json\"-Datei erleichtert die Organisation von Projekten, die sowohl TypeScript- als auch JavaScript-Dateien enthalten. Weitere Informationen finden Sie unter https://aka.ms/tsconfig.", "Additional_Checks_6176": "Zusätzliche Überprüfungen", "Advanced_Options_6178": "Erweiterte Optionen", "All_declarations_of_0_must_have_identical_modifiers_2687": "Alle Deklarationen von \"{0}\" müssen identische Modifizierer aufweisen.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Ein Indexsignaturparameter darf keinen Zugriffsmodifizierer besitzen.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Ein Indexsignaturparameter darf keinen Initialisierer besitzen.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Ein Indexsignaturparameter muss eine Typanmerkung besitzen.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Ein Indexsignaturparametertyp darf kein Typalias sein. Erwägen Sie stattdessen die Schreibung \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Ein Indexsignaturparametertyp darf kein Union-Typ sein. Erwägen Sie stattdessen die Verwendung eines zugeordneten Objekttyps.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Ein Indexsignaturparameter-Typ muss \"string\" oder \"number\" sein.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Eine Schnittstelle kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten erweitern.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Eine Schnittstelle kann nur eine Klasse oder eine andere Schnittstelle erweitern.", @@ -165,7 +169,7 @@ "Binary_digit_expected_1177": "Es wurde eine Binärzahl erwartet.", "Binding_element_0_implicitly_has_an_1_type_7031": "Das Bindungselement \"{0}\" weist implizit einen Typ \"{1}\" auf.", "Block_scoped_variable_0_used_before_its_declaration_2448": "Die blockbezogene Variable \"{0}\" wurde vor ihrer Deklaration verwendet.", - "Call_decorator_expression_90028": "Rufen Sie den Decoratorausdruck auf.", + "Call_decorator_expression_90028": "Decorator-Ausdruck aufrufen", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Eine Aufrufsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", "Call_target_does_not_contain_any_signatures_2346": "Das Aufrufziel enthält keine Signaturen.", "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713": "Der Zugriff auf \"{0}.{1}\" ist nicht möglich, da \"{0}\" ein Typ ist, aber kein Namespace. Wollten Sie den Typ der Eigenschaft \"{1}\" in \"{0}\" mit \"{0}[\"{1}\"]\" abrufen?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Typdeklarationsdateien können nicht importiert werden. Importieren Sie ggf. \"{0}\" anstelle von \"{1}\".", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Die Variable \"{0}\" mit dem äußeren Bereich im gleichen Bereich wie die Deklaration \"{1}\" mit dem Blockbereich kann nicht initialisiert werden.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Ein Ausdruck, dessen Typ eine Aufrufsignatur fehlt, kann nicht aufgerufen werden. Der Typ \"{0}\" weist keine kompatiblen Aufrufsignaturen auf.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Ein Objekt, das möglicherweise NULL ist, kann nicht aufgerufen werden.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Ein Objekt, das möglicherweise NULL oder nicht definiert ist, kann nicht aufgerufen werden.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Ein Objekt, das möglicherweise nicht definiert ist, kann nicht aufgerufen werden.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Ein Typ kann nicht erneut exportiert werden, wenn das Flag \"--isolatedModules\" angegeben ist.", "Cannot_read_file_0_Colon_1_5012": "Die Datei \"{0}\" kann nicht gelesen werden: {1}", "Cannot_redeclare_block_scoped_variable_0_2451": "Die blockbezogene Variable \"{0}\" Blockbereich kann nicht erneut deklariert werden.", @@ -210,9 +217,9 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Die Datei \"{0}\" kann nicht geschrieben werden, da sie eine Eingabedatei überschreiben würde.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Die Variable der Catch-Klausel darf keine Typanmerkung aufweisen.", "Catch_clause_variable_cannot_have_an_initializer_1197": "Die Variable der Catch-Klausel darf keinen Initialisierer aufweisen.", - "Change_0_to_1_90014": "Ändern Sie \"{0}\" in \"{1}\".", + "Change_0_to_1_90014": "\"{0}\" in \"{1}\" ändern", "Change_extends_to_implements_90003": "\"extends\" in \"implements\" ändern", - "Change_spelling_to_0_90022": "Ändern Sie die Schreibweise in \"{0}\".", + "Change_spelling_to_0_90022": "Schreibweise in \"{0}\" ändern", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "Es wird überprüft, ob \"{0}\" das längste übereinstimmende Präfix für \"{1}\"–\"{2}\" ist.", "Circular_definition_of_import_alias_0_2303": "Zirkuläre Definition des Importalias \"{0}\".", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Eine Zirkularität wurde beim Auflösen der Konfiguration erkannt: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Die Klasse \"{0}\" definiert die Instanzmemberfunktion \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Membereigenschaft.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Die Klasse \"{0}\" definiert die Instanzmembereigenschaft \"{1}\", die erweiterte Klasse \"{2}\" definiert diese jedoch als Instanzmemberfunktion.", "Class_0_incorrectly_extends_base_class_1_2415": "Die Klasse \"{0}\" erweitert fälschlicherweise die Basisklasse \"{1}\".", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Die Klasse \"{0}\" implementiert fälschlicherweise die Klasse \"{1}\". Wollten Sie \"{1}\" erweitern und ihre Member als Unterklasse vererben?", "Class_0_incorrectly_implements_interface_1_2420": "Die Klasse \"{0}\" implementiert fälschlicherweise die Schnittstelle \"{1}\".", "Class_0_used_before_its_declaration_2449": "Klasse \"{0}\", die vor der Deklaration verwendet wurde.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Klassendeklarationen dürfen maximal ein \"@augments\"- oder \"@extends\"-Tag aufweisen.", @@ -234,7 +242,7 @@ "Compiler_option_0_expects_an_argument_6044": "Die Compileroption \"{0}\" erwartet ein Argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Die Compileroption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", "Computed_property_names_are_not_allowed_in_enums_1164": "Berechnete Eigenschaftennamen sind in Enumerationen unzulässig.", - "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Berechnete Werte sind in einer Aufzählung mit Membern mit Zeichenfolgenwerten nicht zulässig.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Berechnete Werte sind in einer Enumeration mit Membern mit Zeichenfolgenwerten nicht zulässig.", "Concatenate_and_emit_output_to_single_file_6001": "Verketten und Ausgabe in einer Datei speichern.", "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "In Konflikt stehende Definitionen für \"{0}\" wurden unter \"{1}\" und \"{2}\" gefunden. Installieren Sie ggf. eine bestimmte Version dieser Bibliothek, um den Konflikt aufzulösen.", "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Eine Konstruktsignatur ohne Rückgabetypanmerkung weist implizit einen any-Rückgabetyp auf.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Die enthaltene Datei wird nicht angegeben, und das Stammverzeichnis kann nicht ermittelt werden. Die Suche im Ordner \"node_modules\" wird übersprungen.", "Convert_function_0_to_class_95002": "Funktion \"{0}\" in Klasse konvertieren", "Convert_function_to_an_ES2015_class_95001": "Funktion in eine ES2015-Klasse konvertieren", + "Convert_to_ES6_module_95017": "In ES6-Modul konvertieren", "Convert_to_default_import_95013": "In Standardimport konvertieren", "Corrupted_locale_file_0_6051": "Die Gebietsschemadatei \"{0}\" ist beschädigt.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Es wurde keine Deklarationsdatei für das Modul \"{0}\" gefunden. \"{1}\" weist implizit den Typ \"any\" auf.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Es wurde eine Deklaration erwartet.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Der Deklarationsname steht in Konflikt mit dem integrierten globalen Bezeichner \"{0}\".", "Declaration_or_statement_expected_1128": "Es wurde eine Deklaration oder Anweisung erwartet.", - "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}\".", + "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": "Statische Eigenschaft \"{0}\" deklarieren", "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}\".", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Veraltet] Verwenden Sie stattdessen \"--skipLibCheck\". Überspringen Sie die Typüberprüfung der Standardbibliothek-Deklarationsdateien.", "Digit_expected_1124": "Eine Ziffer wurde erwartet.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Das Verzeichnis \"{0}\" ist nicht vorhanden, Suchvorgänge darin werden übersprungen.", - "Disable_checking_for_this_file_90018": "Überprüfung für diese Datei deaktivieren.", + "Disable_checking_for_this_file_90018": "Überprüfung für diese Datei deaktivieren", "Disable_size_limitations_on_JavaScript_projects_6162": "Größenbeschränkungen für JavaScript-Projekte deaktivieren.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Deaktivieren Sie die strenge Überprüfung generischer Signaturen in Funktionstypen.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Verweise mit uneinheitlicher Groß-/Kleinschreibung auf die gleiche Datei nicht zulassen.", @@ -309,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Aktivieren Sie die strenge Überprüfung der Eigenschafteninitialisierung in Klassen.", "Enable_strict_null_checks_6113": "Strenge NULL-Überprüfungen aktivieren.", "Enable_tracing_of_the_name_resolution_process_6085": "Ablaufverfolgung des Namensauflösungsvorgangs aktivieren.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Ermöglicht Ausgabeinteroperabilität zwischen CommonJS- und ES-Modulen durch die Erstellung von Namespaceobjekten für alle Importe. Impliziert \"AllowSyntheticDefaultImports\".", "Enables_experimental_support_for_ES7_async_functions_6068": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Funktionen.", "Enables_experimental_support_for_ES7_decorators_6065": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Decorators.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Ermöglicht experimentelle Unterstützung zum Ausgeben von Typmetadaten für Decorators.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Der Dateiname \"{0}\" unterscheidet sich vom bereits enthaltenen Dateinamen \"{1}\" nur hinsichtlich der Groß-/Kleinschreibung.", "File_name_0_has_a_1_extension_stripping_it_6132": "Der Dateiname \"{0}\" weist eine Erweiterung \"{1}\" auf. Diese wird entfernt.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Die Dateispezifikation darf kein übergeordnetes Verzeichnis (\"..\") enthalten, das nach einem rekursiven Verzeichnisplatzhalter (\"**\") angegeben wird: \"{0}\".", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Die Dateispezifikation darf nicht mehrere rekursive Verzeichnisplatzhalter enthalten (\"**\"): \"{0}\".", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Die Dateispezifikation darf nicht mit einem rekursiven Verzeichnisplatzhalter (\"**\") enden: \"{0}\".", "Found_package_json_at_0_6099": "\"package.json\" wurde unter \"{0}\" gefunden.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Funktionsdeklarationen sind in Blöcken im Strict-Modus unzulässig, wenn das Ziel \"ES3\" oder \"ES5\" ist.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Es wurde ein Bezeichner erwartet. \"{0}\" ist ein reserviertes Wort im Strict-Modus. Module befinden sich automatisch im Strict-Modus.", "Identifier_expected_1003": "Es wurde ein Bezeichner erwartet.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Bezeichner erwartet. \"__esModule\" ist als exportierter Marker für die Umwandlung von ECMAScript-Modulen reserviert.", - "Ignore_this_error_message_90019": "Diese Fehlermeldung ignorieren.", + "Ignore_this_error_message_90019": "Diese Fehlermeldung ignorieren", "Implement_inherited_abstract_class_90007": "Geerbte abstrakte Klasse implementieren", "Implement_interface_0_90006": "Schnittstelle \"{0}\" implementieren", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Die implements-Klausel der exportierten Klasse \"{0}\" besitzt oder verwendet den privaten Namen \"{1}\".", - "Import_0_from_module_1_90013": "Import von \"{0}\" aus Modul \"{1}\".", + "Import_0_from_module_1_90013": "\"{0}\" aus dem Modul \"{1}\" importieren", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Die Importzuweisung kann nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" oder ein anderes Modulformat.", "Import_declaration_0_is_using_private_name_1_4000": "Die Importdeklaration \"{0}\" verwendet den privaten Namen \"{1}\".", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Die Importdeklaration verursacht einen Konflikt mit der lokalen Deklaration von \"{0}\".", @@ -424,10 +433,10 @@ "Index_signature_is_missing_in_type_0_2329": "Die Indexsignatur fehlt im Typ \"{0}\".", "Index_signatures_are_incompatible_2330": "Die Indexsignaturen sind nicht kompatibel.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Einzelne Deklarationen in der gemergten Deklaration \"{0}\" müssen alle exportiert oder alle lokal sein.", - "Infer_parameter_types_from_usage_95012": "Leiten Sie Parametertypen aus der Nutzung ab.", - "Infer_type_of_0_from_usage_95011": "Leiten Sie den Typ von \"{0}\" aus der Nutzung ab.", - "Initialize_property_0_in_the_constructor_90020": "Eigenschaft '{0}' im Konstruktor initialisieren.", - "Initialize_static_property_0_90021": "Statische Eigenschaft '{0}' initialisieren.", + "Infer_parameter_types_from_usage_95012": "Parametertypen aus der Nutzung ableiten", + "Infer_type_of_0_from_usage_95011": "Typ von \"{0}\" aus der Nutzung ableiten", + "Initialize_property_0_in_the_constructor_90020": "Eigenschaft \"{0}\" im Konstruktor initialisieren", + "Initialize_static_property_0_90021": "Statische Eigenschaft \"{0}\" initialisieren", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Der Initialisierer der Instanzmembervariablen \"{0}\" darf nicht auf den im Konstruktor deklarierten Bezeichner \"{1}\" verweisen.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Der Initialisierer des Parameters \"{0}\" darf nicht auf den anschließend deklarierten Bezeichner \"{1}\" verweisen.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Der Initialisierer stellt keinen Wert für dieses Bindungselement bereit, und das Bindungselement besitzt keinen Standardwert.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Für das Gebietsschema ist das Format oder - erforderlich, z. B. \"{0}\" oder \"{1}\".", "Longest_matching_prefix_for_0_is_1_6108": "Das längste übereinstimmende Präfix für \"{0}\" ist \"{1}\".", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Die Suche erfolgt im Ordner \"node_modules\". Anfangsspeicherort \"{0}\".", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Legen Sie den super()-Aufruf als erste Anweisung im Konstruktor fest.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "super()-Aufruf als erste Anweisung im Konstruktor festlegen", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Der zugeordnete Objekttyp weist implizit einen any-Vorlagentyp auf.", "Member_0_implicitly_has_an_1_type_7008": "Der Member \"{0}\" weist implizit den Typ \"{1}\" auf.", "Merge_conflict_marker_encountered_1185": "Mergekonfliktmarkierung", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Die gemergte Deklaration \"{0}\" darf keine Exportstandarddeklaration enthalten. Fügen Sie ggf. eine separate Deklaration \"export default {0}\" hinzu.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Der Modulname \"{0}\" wurde erfolgreich in \"{1}\" aufgelöst. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Die Art der Modulauflösung wird nicht angegeben. \"{0}\" wird verwendet.", "Module_resolution_using_rootDirs_has_failed_6111": "Fehler bei der Modulauflösung mithilfe von \"rootDirs\".", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Mehrere aufeinander folgende numerische Trennzeichen sind nicht zulässig.", "Multiple_constructor_implementations_are_not_allowed_2392": "Mehrere Konstruktorimplementierungen sind unzulässig.", "NEWLINE_6061": "NEUE ZEILE", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Die benannte Eigenschaft \"{0}\" der Typen \"{1}\" und \"{2}\" ist nicht identisch.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Der nicht abstrakte Ausdruck implementiert nicht den geerbten abstrakten Member \"{0}\" aus der Klasse \"{1}\".", "Not_all_code_paths_return_a_value_7030": "Nicht alle Codepfade geben einen Wert zurück.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Der numerische Indextyp \"{0}\" kann dem Zeichenfolgen-Indextyp \"{1}\" nicht zugewiesen werden.", + "Numeric_separators_are_not_allowed_here_6188": "Numerische Trennzeichen sind hier nicht zulässig.", "Object_is_possibly_null_2531": "Das Objekt ist möglicherweise \"NULL\".", "Object_is_possibly_null_or_undefined_2533": "Das Objekt ist möglicherweise \"NULL\" oder \"nicht definiert\".", "Object_is_possibly_undefined_2532": "Das Objekt ist möglicherweise \"nicht definiert\".", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Der Parametertyp des öffentlichen statischen Setters \"{0}\" aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Im Strict-Modus analysieren und \"use strict\" für jede Quelldatei ausgeben.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Das Muster \"{0}\" darf höchstens ein Zeichen \"*\" aufweisen.", - "Prefix_0_with_an_underscore_90025": "Präfix \"{0}\" mit einem Unterstrich.", + "Prefix_0_with_an_underscore_90025": "\"{0}\" einen Unterstrich voranstellen", "Print_names_of_files_part_of_the_compilation_6155": "Drucknamen des Dateiteils der Kompilierung.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Drucknamen des generierten Dateiteils der Kompilierung.", "Print_the_compiler_s_version_6019": "Die Version des Compilers ausgeben.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist im Konstruktor nicht definitiv zugewiesen.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem get-Accessor eine Parametertypanmerkung fehlt.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem set-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann nicht der gleichen Eigenschaft in Basistyp \"{2}\" zugewiesen werden.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann dem Typ \"{2}\" nicht zugewiesen werden.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Die Eigenschaft \"{0}\" ist deklariert, aber ihr Wert wird nie gelesen.", "Property_0_is_incompatible_with_index_signature_2530": "Die Eigenschaft \"{0}\" ist nicht mit der Indexsignatur kompatibel.", @@ -635,6 +648,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Fehler für \"this\"-Ausdrücke mit einem impliziten any-Typ auslösen.", "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", "Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}", + "Replace_import_with_0_95015": "Ersetzen Sie den Import durch \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Fehler melden, wenn nicht alle Codepfade in der Funktion einen Wert zurückgeben.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Für FallTrough-Fälle in switch-Anweisung Fehler melden.", "Report_errors_in_js_files_8019": "Fehler in .js-Dateien melden.", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Der Rückgabetyp der öffentlichen statischen Methode aus der exportierten Klasse besitzt oder verwendet den privaten Namen \"{0}\".", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Modulauflösungen aus \"{0}\" werden wiederverwendet, da Auflösungen aus dem alten Programm nicht geändert wurden.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Die Auflösung des Moduls \"{0}\" in die Datei \"{1}\" aus dem alten Programm wird wiederverwendet.", - "Rewrite_as_the_indexed_access_type_0_90026": "Als indizierten Zugriffstyp \"{0}\" neu schreiben.", + "Rewrite_as_the_indexed_access_type_0_90026": "Als indizierten Zugriffstyp \"{0}\" neu schreiben", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Das Stammverzeichnis kann nicht ermittelt werden. Die primären Suchpfade werden übersprungen.", "STRATEGY_6039": "STRATEGIE", "Scoped_package_detected_looking_in_0_6182": "Bereichsbezogenes Paket erkannt. In \"{0}\" wird gesucht", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Quellzuordnungsoptionen", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Eine spezialisierte Überladungssignatur kann keiner nicht spezialisierten Signatur zugewiesen werden.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Der Spezifizierer des dynamischen Imports darf kein Spread-Element sein.", - "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_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript-Zielversion angeben: ES3 (Standard), ES5, ES2015, ES2016, ES2017, ES2018 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": "Geben Sie die Codegenerierung für das Modul an: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\" oder \"ESNext\".", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Geben Sie das Stammverzeichnis der Eingabedateien an. Verwenden Sie diese Angabe, um die Ausgabeverzeichnisstruktur mithilfe von \"-outDir\" zu steuern.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Der Verteilungsoperator in new-Ausdrücken ist nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", "Spread_types_may_only_be_created_from_object_types_2698": "Spread-Typen dürfen nur aus object-Typen erstellt werden.", + "Starting_compilation_in_watch_mode_6031": "Kompilierung im Überwachungsmodus wird gestartet...", "Statement_expected_1129": "Eine Anweisung wurde erwartet.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Anweisungen sind in Umgebungskontexten unzulässig.", "Static_members_cannot_reference_class_type_parameters_2302": "Statische Member dürfen nicht auf Klassentypparameter verweisen.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Ein Zeichenfolgenliteral wurde erwartet.", "String_literal_with_double_quotes_expected_1327": "Ein Zeichenfolgenliteral mit doppelten Anführungszeichen wird erwartet.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Fehler und Nachrichten farbig und mit Kontext formatieren (experimentell).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Nachfolgende Eigenschaftendeklarationen müssen den gleichen Typ aufweisen. Die Eigenschaft \"{0}\" muss den Typ \"{1}\" aufweisen, ist hier aber vom Typ \"{2}\".", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Nachfolgende Variablendeklarationen müssen den gleichen Typ aufweisen. Die Variable \"{0}\" muss den Typ \"{1}\" aufweisen, ist hier aber vom Typ \"{2}\".", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Die Ersetzung \"{0}\" für das Muster \"{1}\" weist einen falschen Typ auf. Erwartet wurde \"string\", abgerufen wurde \"{2}\".", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Die Ersetzung \"{0}\" im Muster \"{1}\" darf höchstens ein Zeichen \"*\" aufweisen.", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ \"{0}\" ist kein Array-Typ oder Zeichenfolgentyp oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ \"{0}\" ist kein Array-Typ oder weist keine \"[Symbol.iterator]()\"-Methode auf, die einen Iterator zurückgibt.", "Type_0_is_not_assignable_to_type_1_2322": "Der Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Typ \"{0}\" kann nicht zu Typ \"{1}\" zugewiesen werden. Es sind zwei verschiedene Typen mit diesem Namen vorhanden, diese sind jedoch nicht verwandt.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Der Typ \"{0}\" kann dem Typ \"{1}\" nicht zugewiesen werden. Es sind zwei verschiedene Typen mit diesem Namen vorhanden, diese sind jedoch nicht verwandt.", "Type_0_is_not_comparable_to_type_1_2678": "Der Typ \"{0}\" kann nicht mit dem Typ \"{1}\" verglichen werden.", "Type_0_is_not_generic_2315": "Der Typ \"{0}\" ist nicht generisch.", "Type_0_provides_no_match_for_the_signature_1_2658": "Der Typ \"{0}\" enthält keine Entsprechung für die Signatur \"{1}\".", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Nicht abgeschlossenes Vorlagenliteral.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Nicht typisierte Funktionsaufrufe dürfen keine Typargumente annehmen.", "Unused_label_7028": "Nicht verwendete Bezeichnung.", + "Use_synthetic_default_member_95016": "Verwenden Sie den synthetischen Member \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Das Verwenden einer Zeichenfolge in einer for...of-Anweisung wird nur in ECMAScript 5 oder höher unterstützt.", "VERSION_6036": "VERSION", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Der Wert des Typs \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit dem Typ \"{1}\". Wollten Sie ihn aufrufen?", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 1cc79da620336..65e40e37f9578 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -303,6 +303,12 @@ + + + + + + @@ -363,6 +369,12 @@ + + + + + + @@ -567,6 +579,12 @@ + + + + + + @@ -831,6 +849,18 @@ + + + + + + + + + + + + @@ -1191,6 +1221,24 @@ + + + + + + + + + + + + + + + + + + @@ -1341,6 +1389,12 @@ + + + + + + @@ -1485,6 +1539,12 @@ + + + + + + @@ -1869,6 +1929,12 @@ + + + + + + @@ -2127,12 +2193,6 @@ - - - - - - @@ -2241,12 +2301,6 @@ - - - - - - @@ -2259,6 +2313,12 @@ + + + + + + @@ -2925,6 +2985,12 @@ + + + + + + @@ -3063,6 +3129,12 @@ + + + + + + @@ -3123,6 +3195,12 @@ + + + + + + @@ -3591,6 +3669,12 @@ + + + + + + @@ -3825,6 +3909,12 @@ + + + + + + @@ -4185,9 +4275,9 @@ - + - + @@ -4245,6 +4335,12 @@ + + + + + + @@ -5163,6 +5259,12 @@ + + + + + + @@ -5495,7 +5597,7 @@ - + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 8f12067127703..3ac8faf7afddd 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -42,17 +42,18 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "Un generador no puede tener una anotación de tipo \"void\".", "A_get_accessor_cannot_have_parameters_1054": "Un descriptor de acceso \"get\" no puede tener parámetros.", "A_get_accessor_must_return_a_value_2378": "Un descriptor de acceso \"get\" debe devolver un valor.", - "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inicializador de miembro de una declaración enum no puede hacer referencia a los miembros que se declaran después de este, incluidos aquellos definidos en otras enumeraciones.", - "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una clase mixin debe tener un constructor con un parámetro de REST sencillo del tipo \"any[]\".", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inicializador de miembro de una declaración de enumeración no puede hacer referencia a los miembros que se declaran después de este, incluidos aquellos definidos en otras enumeraciones.", + "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una clase mixin debe tener un constructor con un solo parámetro rest de tipo \"any[]\"", "A_module_cannot_have_multiple_default_exports_2528": "Un módulo no puede tener varias exportaciones predeterminadas.", "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una declaración de espacio de nombres no puede estar en un archivo distinto de una clase o función con la que se combina.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una declaración de espacio de nombres no se puede situar antes que una clase o función con la que se combina.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una declaración de espacio de nombres solo se permite en un espacio de nombres o en un módulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "No se puede llamar o construir una importación de estilo de espacio de nombres, y provocará un error en tiempo de ejecución.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inicializador de parámetros solo se permite en una implementación de función o de constructor.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Una propiedad de parámetro no se puede declarar mediante un parámetro rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una propiedad de parámetro solo se permite en una implementación de constructor.", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Una propiedad de parámetro podría no declararse mediante un patrón de enlace.", - "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Una ruta de acceso en una opción \"extiende\" debe ser relativa o raíz, pero no '{0}'.", + "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Una ruta de acceso en una opción \"extiende\" debe ser relativa o raíz, pero no \"{0}\".", "A_promise_must_have_a_then_method_1059": "Una promesa debe tener un método \"then\".", "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Una propiedad de una clase cuyo tipo sea \"unique symbol\" debe ser \"static\" y \"readonly\".", "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Una propiedad de una interfaz o un literal de tipo cuyo tipo sea \"unique symbol\" debe ser \"readonly\".", @@ -91,11 +92,12 @@ "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.", - "Add_0_to_existing_import_declaration_from_1_90015": "Agregue \"{0}\" a una declaración de importación existente desde \"{1}\".", - "Add_index_signature_for_property_0_90017": "Agregue una firma de índice para la propiedad \"{0}\".", - "Add_missing_super_call_90001": "Agregue la llamada a \"super()\" que falta.", - "Add_this_to_unresolved_variable_90008": "Agrega \"this.\" a una variable no resuelta.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Agregar un archivo tsconfig.json ayuda a organizar los proyectos que contienen archivos TypeScript y JavaScript. Más información en https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "Agregar \"{0}\" a una declaración de importación existente desde \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Agregar el modificador async a la función contenedora", + "Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"", + "Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta", + "Add_this_to_unresolved_variable_90008": "Agregar \"this.\" a una variable no resuelta", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Agregar un archivo tsconfig.json ayuda a organizar los proyectos que contienen archivos TypeScript y JavaScript. Más información en https://aka.ms/tsconfig.", "Additional_Checks_6176": "Comprobaciones adicionales", "Advanced_Options_6178": "Opciones avanzadas", "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas las declaraciones de '{0}' deben tener modificadores idénticos.", @@ -111,7 +113,7 @@ "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Un descriptor de acceso no se puede declarar en un contexto de ambiente.", "An_accessor_cannot_have_type_parameters_1094": "Un descriptor de acceso no puede tener parámetros de tipo.", "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una declaración de módulo de ambiente solo se permite en el nivel superior de un archivo.", - "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmético debe ser de tipo \"any\", \"number\" o de tipo enum.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmético debe ser de tipo \"any\", \"number\" o un tipo de enumeración.", "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Una función o un método de asincronía en ES5/ES3 requiere el constructor \"Promise\". Asegúrese de que tiene una declaración para el constructor \"Promise\" o incluya \"ES2015\" en su opción \"--lib\".", "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Una función o un método asincrónico deben tener un tipo de valor devuelto válido que admita await.", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Una función o un método asincrónicos deben devolver una \"promesa\". Asegúrese de que hay una declaración de \"promesa\" o incluya \"ES2015\" en la opción \"--lib\".", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parámetro de signatura de índice no puede tener un modificador de accesibilidad.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parámetro de signatura de índice no puede tener un inicializador.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parámetro de signatura de índice debe tener una anotación de tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un tipo de parámetro de firma de índice no puede ser un alias de tipo. Considere la posibilidad de escribir en su lugar \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un tipo de parámetro de firma de índice no puede ser un tipo de unión. Considere la posibilidad de usar en su lugar un tipo de objeto asignado.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "El tipo de un parámetro de signatura de índice debe ser \"string\" o \"number\".", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Una interfaz solo puede extender un identificador o nombre completo con argumentos de tipo opcional.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Una interfaz solo puede extender una clase u otra interfaz.", @@ -150,8 +154,8 @@ "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}'.", + "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}\".", "Array_element_destructuring_pattern_expected_1181": "Se esperaba un patrón de desestructuración de elementos de matriz.", "Asterisk_Slash_expected_1010": "Se esperaba \"*/\".", "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "Los aumentos del ámbito global solo pueden anidarse directamente en módulos externos o en declaraciones de módulos de ambiente.", @@ -165,7 +169,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_decorator_expression_90028": "Llamar 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}\"]\"?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "No se pueden importar archivos de declaración de tipos. Considere importar \"{0}\" en lugar de \"{1}\".", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "No se puede inicializar la variable '{0}' de ámbito externo en el mismo ámbito que la declaración '{1}' con ámbito de bloque.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "No se puede invocar una expresión con un tipo sin signatura de llamada. El tipo '{0}' no tiene ninguna signatura de llamada compatible.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "No se puede invocar un objeto que es posiblemente \"null\".", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "No se puede invocar un objeto que es posiblemente \"null\" o \"no definido\".", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "No se puede invocar un objeto que es posiblemente \"no definido\".", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "No se puede volver a exportar un tipo si se proporciona la marca \"--isolatedModules\".", "Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.", @@ -210,9 +217,9 @@ "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": "Cambie \"{0}\" a \"{1}\".", - "Change_extends_to_implements_90003": "Cambiar \"extends\" por \"implements\".", - "Change_spelling_to_0_90022": "Cambiar la ortografía a \"{0}\".", + "Change_0_to_1_90014": "Cambiar \"{0}\" a \"{1}\"", + "Change_extends_to_implements_90003": "Cambiar \"extends\" a \"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}'.", "Circular_definition_of_import_alias_0_2303": "Definición circular del alias de importación '{0}'.", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Se detectó circularidad al resolver la configuración: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La clase '{0}' define la función miembro de instancia como '{1}', pero la clase extendida '{2}' la define como propiedad de miembro de instancia.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La clase '{0}' define la propiedad de miembro de instancia como '{1}', pero la clase extendida '{2}' la define como función miembro de instancia.", "Class_0_incorrectly_extends_base_class_1_2415": "La clase '{0}' extiende la clase base '{1}' de forma incorrecta.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La clase \"{0}\" no implementa correctamente la clase \"{1}\". ¿Pretendía extender \"{1}\" y heredar sus miembros como una subclase?", "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\".", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "El archivo contenedor no se ha especificado y no se puede determinar el directorio raíz. Se omitirá la búsqueda en la carpeta 'node_modules'.", "Convert_function_0_to_class_95002": "Convertir la función \"{0}\" en una clase", "Convert_function_to_an_ES2015_class_95001": "Convertir la función en una clase ES2015", + "Convert_to_ES6_module_95017": "Convertir en módulo ES6", "Convert_to_default_import_95013": "Convertir en importación predeterminada", "Corrupted_locale_file_0_6051": "Archivo de configuración regional {0} dañado.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "No se encontró ningún archivo de declaración para el módulo '{0}'. '{1}' tiene un tipo \"any\" de forma implícita.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Se esperaba una declaración.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Conflictos entre nombres de declaración con el identificador global '{0}' integrado.", "Declaration_or_statement_expected_1128": "Se esperaba una declaración o una instrucción.", - "Declare_method_0_90023": "Declare el método \"{0}\".", - "Declare_property_0_90016": "Declare la propiedad \"{0}\".", - "Declare_static_method_0_90024": "Declare el método estático \"{0}\".", - "Declare_static_property_0_90027": "Declare la propiedad \"{0}\" estática.", + "Declare_method_0_90023": "Declarar el método \"{0}\"", + "Declare_property_0_90016": "Declarar la propiedad \"{0}\"", + "Declare_static_method_0_90024": "Declarar el método estático \"{0}\"", + "Declare_static_property_0_90027": "Declarar la propiedad estática \"{0}\"", "Decorators_are_not_valid_here_1206": "Los elementos Decorator no son válidos aquí.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "No se pueden aplicar elementos Decorator a varios descriptores de acceso get o set con el mismo nombre.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "La exportación predeterminada del módulo tiene o usa el nombre privado '{0}'.", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[En desuso] Use \"--skipLibCheck\" en su lugar. Omite la comprobación de tipos de los archivos de declaración de biblioteca predeterminados.", "Digit_expected_1124": "Se esperaba un dígito.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "El directorio \"{0}\" no existe, se omitirán todas las búsquedas en él.", - "Disable_checking_for_this_file_90018": "Deshabilite la comprobación para este archivo.", + "Disable_checking_for_this_file_90018": "Deshabilitar la comprobación para este archivo", "Disable_size_limitations_on_JavaScript_projects_6162": "Deshabilitar los límites de tamaño de proyectos de JavaScript.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Deshabilite la comprobación estricta de firmas genéricas en tipos de función.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "No permitir referencias al mismo archivo con un uso incoherente de mayúsculas y minúsculas.", @@ -309,15 +318,16 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite la comprobación estricta de inicialización de propiedades en las clases.", "Enable_strict_null_checks_6113": "Habilitar comprobaciones estrictas de elementos nulos.", "Enable_tracing_of_the_name_resolution_process_6085": "Habilitar seguimiento del proceso de resolución de nombres.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Permite emitir interoperabilidad entre módulos CommonJS y ES mediante la creación de objetos de espacio de nombres para todas las importaciones. Implica \"allowSyntheticDefaultImports\".", "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita la compatibilidad experimental con las funciones asincrónicas de ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Habilita la compatibilidad experimental con los elementos Decorator de ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita la compatibilidad experimental para emitir metadatos de tipo para los elementos Decorator.", "Enum_0_used_before_its_declaration_2450": "Se ha usado la enumeración \"{0}\" antes de declararla.", - "Enum_declarations_must_all_be_const_or_non_const_2473": "Todas las declaraciones enum deben ser de tipo const o no const.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Todas las declaraciones de enumeración deben ser de tipo const o no const.", "Enum_member_expected_1132": "Se esperaba un miembro de enumeración.", "Enum_member_must_have_initializer_1061": "El miembro de enumeración debe tener un inicializador.", "Enum_name_cannot_be_0_2431": "El nombre de la enumeración no puede ser \"{0}\".", - "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Tipo enum '{0}' tiene miembros con inicializadores que no son literales.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "El tipo de enumeración \"{0}\" tiene miembros con inicializadores que no son literales.", "Examples_Colon_0_6026": "Ejemplos: {0}", "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profundidad excesiva de la pila al comparar los tipos '{0}' y '{1}'.", "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Se esperaban argumentos de tipo {0}-{1}; proporciónelos con una etiqueta \"@extends\".", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "El nombre de archivo \"{0}\" es diferente del nombre de archivo \"{1}\" ya incluido solo en el uso de mayúsculas y minúsculas.", "File_name_0_has_a_1_extension_stripping_it_6132": "El nombre de archivo \"{0}\" tiene una extensión \"{1}\" y se va a quitar.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La especificación del archivo no puede contener un directorio primario ('..') que aparezca después de un comodín de directorios recursivo ('**'): '{0}'.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "La especificación de archivo no puede contener varios comodines de directorio recursivo ('**'): '{0}'.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La especificación de archivo no puede finalizar en un comodín de directorio recursivo ('**'): '{0}'.", "Found_package_json_at_0_6099": "Se encontró 'package.json' en '{0}'.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "No se permiten declaraciones de función en bloques en modo strict cuando el destino es 'ES3' o 'ES5'.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Se esperaba un identificador. '{0}' es una palabra reservada en modo strict. Los módulos están en modo strict automáticamente.", "Identifier_expected_1003": "Se esperaba un identificador.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. \"__esModule\" está reservado como marcador exportado al transformar módulos ECMAScript.", - "Ignore_this_error_message_90019": "Ignore este mensaje de error.", - "Implement_inherited_abstract_class_90007": "Implementar clase abstracta heredada.", - "Implement_interface_0_90006": "Implementar interfaz \"{0}\".", + "Ignore_this_error_message_90019": "Ignorar este mensaje de error", + "Implement_inherited_abstract_class_90007": "Implementar clase abstracta heredada", + "Implement_interface_0_90006": "Implementar la interfaz \"{0}\"", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La cláusula implements de la clase '{0}' exportada tiene o usa el nombre privado '{1}'.", - "Import_0_from_module_1_90013": "Importar \"{0}\" desde el módulo \"{1}\".", + "Import_0_from_module_1_90013": "Importar \"{0}\" desde el módulo \"{1}\"", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "No se puede usar una asignación de importación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"import * as ns from 'mod'\", \"import {a} from 'mod'\", \"import d from 'mod'\" u otro formato de módulo en su lugar.", "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", @@ -417,17 +426,17 @@ "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "No se permiten importaciones en aumentos de módulos. Considere la posibilidad de moverlas al módulo externo envolvente.", - "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones enum de ambiente, el inicializador de miembro debe ser una expresión constante.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "En las declaraciones de enumeración de ambiente, el inicializador de miembro debe ser una expresión constante.", "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "En una enumeración con varias declaraciones, solo una declaración puede omitir un inicializador para el primer elemento de la enumeración.", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "El inicializador de miembro de las declaraciones de enumeración \"const\" debe ser una expresión constante.", "Index_signature_in_type_0_only_permits_reading_2542": "La signatura de índice del tipo '{0}' solo permite lectura.", "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}\".", + "Infer_parameter_types_from_usage_95012": "Deducir los tipos de parámetro del uso", + "Infer_type_of_0_from_usage_95011": "Deducir el tipo de \"{0}\" del uso", + "Initialize_property_0_in_the_constructor_90020": "Inicializar la propiedad \"{0}\" en el constructor", + "Initialize_static_property_0_90021": "Inicializar 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.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "El inicializador del parámetro '{0}' no puede hacer referencia al identificador '{1}' declarado después.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "El inicializador no proporciona ningún valor para este elemento de enlace que, a su vez, no tiene un valor predeterminado.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "La configuración regional debe tener el formato o -. Por ejemplo, '{0}' o '{1}'.", "Longest_matching_prefix_for_0_is_1_6108": "El prefijo coincidente más largo para \"{0}\" es \"{1}\".", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Buscando en la carpeta \"node_modules\", ubicación inicial: \"{0}\".", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Haga que la llamada a \"super()\" sea la primera instrucción del constructor.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Hacer que la llamada a \"super()\" sea la primera instrucción del constructor", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "El tipo de objeto asignado tiene implícitamente un tipo de plantilla \"any\".", "Member_0_implicitly_has_an_1_type_7008": "El miembro '{0}' tiene un tipo '{1}' implícitamente.", "Merge_conflict_marker_encountered_1185": "Se encontró un marcador de conflicto de combinación.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La declaración combinada '{0}' no puede incluir una declaración de exportación predeterminada. Considere la posibilidad de agregar una declaración \"export default {0}\" independiente en su lugar.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== El nombre del módulo '{0}' se resolvió correctamente como '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "No se ha especificado el tipo de resolución del módulo, se usará '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "No se pudo resolver el módulo con \"rootDirs\".", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "No se permiten varios separadores numéricos consecutivos.", "Multiple_constructor_implementations_are_not_allowed_2392": "No se permiten varias implementaciones del constructor.", "NEWLINE_6061": "NUEVA LÍNEA", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propiedad '{0}' con nombre de los tipos '{1}' y '{2}' no es idéntica en ambos.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Una expresión de clase no abstracta no implementa el miembro abstracto heredado '{0}' de la clase '{1}'.", "Not_all_code_paths_return_a_value_7030": "No todas las rutas de acceso de código devuelven un valor.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "El tipo de índice numérico '{0}' no se puede asignar a un tipo de índice de cadena '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "Aquí no se permiten separadores numéricos.", "Object_is_possibly_null_2531": "El objeto es posiblemente \"null\".", "Object_is_possibly_null_or_undefined_2533": "El objeto es posiblemente \"null\" o \"undefined\".", "Object_is_possibly_undefined_2532": "El objeto es posiblemente \"undefined\".", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "El tipo de parámetro del establecedor estático público \"{0}\" de la clase exportada tiene o usa el nombre privado \"{1}\".", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analiza en modo strict y emite \"use strict\" para cada archivo de código fuente.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "El patrón \"{0}\" puede tener un carácter '*' como máximo.", - "Prefix_0_with_an_underscore_90025": "Prefijo '{0}' con guion bajo.", + "Prefix_0_with_an_underscore_90025": "Prefijo \"{0}\" con guion bajo", "Print_names_of_files_part_of_the_compilation_6155": "Imprimir los nombres de los archivos que forman parte de la compilación.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimir los nombres de los archivos generados que forman parte de la compilación.", "Print_the_compiler_s_version_6019": "Imprima la versión del compilador.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propiedad \"{0}\" no tiene inicializador y no está asignada de forma definitiva en el constructor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso get le falta una anotación de tipo de valor devuelto.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso set le falta una anotación de tipo de parámetro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar a la misma propiedad del tipo base \"{2}\".", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar al tipo \"{2}\".", "Property_0_is_declared_but_its_value_is_never_read_6138": "La propiedad \"{0}\" se declara, pero su valor no se lee nunca.", "Property_0_is_incompatible_with_index_signature_2530": "La propiedad '{0}' es incompatible con la signatura de índice.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Generar un error en las expresiones y las declaraciones con un tipo \"any\" implícito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Generar un error en expresiones 'this' con un tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", - "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\".", + "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"", + "Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.", "Report_errors_in_js_files_8019": "Notifique los errores de los archivos .js.", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "El tipo de valor devuelto del método estático público de la clase exportada tiene o usa el nombre privado '{0}'.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Las resoluciones de módulo cuyo origen es \"{0}\" se reutilizan, ya que las resoluciones no varían respecto al programa anterior.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Reutilizando la resolución del módulo \"{0}\" en el archivo \"{1}\" del programa anterior.", - "Rewrite_as_the_indexed_access_type_0_90026": "Reescribir como el tipo de acceso indexado \"{0}\".", + "Rewrite_as_the_indexed_access_type_0_90026": "Reescribir como tipo de acceso indexado \"{0}\"", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "No se puede determinar el directorio raíz, se omitirán las rutas de búsqueda principales.", "STRATEGY_6039": "ESTRATEGIA", "Scoped_package_detected_looking_in_0_6182": "Se detectó un paquete con ámbito al buscar en \"{0}\"", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Opciones de mapa de origen", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La signatura de sobrecarga especializada no se puede asignar a ninguna signatura no especializada.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "El especificador de importación dinámica no puede ser un elemento de propagación.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Especifique la versión de ECMAScript de destino: \"ES3\" (valor predeterminado), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\" o \"ESNEXT\".", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Especifique la versión de ECMAScript de destino: \"ES3\" (valor predeterminado), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\", \"ES2018\" o \"ESNEXT\".", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Especifique la generación de código JSX: \"preserve\", \"react-native\" o \"react\".", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Especifique archivos de biblioteca para incluirlos en la compilación: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Especifique la generación de código del módulo: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\" o \"ESNext\".", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Especifique el directorio raíz de los archivos de entrada. Úselo para controlar la estructura del directorio de salida con --outDir.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "El operador spread de las expresiones \"new\" solo está disponible si el destino es ECMAScript 5 y versiones posteriores.", "Spread_types_may_only_be_created_from_object_types_2698": "Los tipos spread solo se pueden crear a partir de tipos de objeto.", + "Starting_compilation_in_watch_mode_6031": "Iniciando la compilación en modo de inspección...", "Statement_expected_1129": "Se esperaba una instrucción.", "Statements_are_not_allowed_in_ambient_contexts_1036": "No se permiten instrucciones en los contextos de ambiente.", "Static_members_cannot_reference_class_type_parameters_2302": "Los miembros estáticos no pueden hacer referencia a parámetros de tipo de clase.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Se esperaba un literal de cadena.", "String_literal_with_double_quotes_expected_1327": "Se esperaba un literal de cadena entre comillas dobles.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Use color y contexto para estilizar los errores y los mensajes (experimental).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Las declaraciones de propiedad subsiguientes deben tener el mismo tipo. La propiedad \"{0}\" debe ser de tipo \"{1}\", pero aquí tiene el tipo \"{2}\".", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Las declaraciones de variable subsiguientes deben tener el mismo tipo. La variable '{0}' debe ser de tipo '{1}', pero aquí tiene el tipo '{2}'.", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "La sustitución '{0}' para el patrón '{1}' tiene un tipo incorrecto. Se esperaba 'string', pero se obtuvo '{2}'.", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La sustitución \"{0}\" del patrón \"{1}\" puede tener un carácter '*' como máximo.", @@ -745,7 +760,7 @@ "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "La parte izquierda de una instrucción \"for...in\" debe ser de tipo \"string\" o \"any\".", "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "La parte izquierda de una instrucción \"for...of\" no puede usar una anotación de tipo.", "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "La parte izquierda de una instrucción 'for...of' debe ser una variable o el acceso a una propiedad.", - "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La parte izquierda de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo enum.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "La parte izquierda de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo de enumeración.", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte izquierda de una expresión de asignación debe ser una variable o el acceso a una propiedad.", "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "La parte izquierda de una expresión \"in\" debe ser de tipo \"any\", \"string\", \"number\" o \"symbol\".", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte izquierda de una expresión \"instanceof\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", @@ -760,7 +775,7 @@ "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "El tipo de valor devuelto de una función asincrónica debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "El tipo de valor devuelto de una función o un método asincrónicos debe ser el tipo Promise global.", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "La parte derecha de una instrucción \"for...in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", - "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La parte derecha de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo enum.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "La parte derecha de una operación aritmética debe ser de tipo \"any\", \"number\" o un tipo de enumeración.", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La parte derecha de una expresión \"in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte derecha de una expresión \"instanceof\" debe ser de tipo \"any\" o un tipo que pueda asignarse al tipo de interfaz \"Function\".", "The_specified_path_does_not_exist_Colon_0_5058": "La ruta de acceso especificada no existe: \"{0}\".", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "El tipo \"{0}\" no es un tipo de matriz o un tipo de cadena o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "El tipo \"{0}\" no es un tipo de matriz o no tiene un método \"[Symbol.iterator]()\" que devuelve un iterador.", "Type_0_is_not_assignable_to_type_1_2322": "El tipo '{0}' no se puede asignar al tipo '{1}'.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "El tipo \"{0}\" no se puede asignar al tipo \"{1}\". Existen dos tipos distintos con este nombre, pero no están relacionados.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "El tipo \"{0}\" no se puede asignar al tipo \"{1}\". Existen dos tipos distintos con este nombre, pero no están relacionados.", "Type_0_is_not_comparable_to_type_1_2678": "El tipo '{0}' no se puede comparar con el tipo '{1}'.", "Type_0_is_not_generic_2315": "El tipo '{0}' no es genérico.", "Type_0_provides_no_match_for_the_signature_1_2658": "El tipo \"{0}\" no proporciona ninguna coincidencia para la signatura \"{1}\".", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Literal de plantilla sin terminar.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Las llamadas a función sin tipo no pueden aceptar argumentos de tipo.", "Unused_label_7028": "Etiqueta no usada.", + "Use_synthetic_default_member_95016": "Use el miembro sintético \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", "VERSION_6036": "VERSIÓN", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "El valor de tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\". ¿Realmente quiere llamarlo?", @@ -913,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Las declaraciones \"const\" deben inicializarse.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor no finito.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor \"NaN\" no permitido.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Las enumeraciones \"const\" solo se pueden usar en expresiones de acceso de propiedad o índice, o en la parte derecha de una declaración de importación o una asignación de exportación.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Las enumeraciones \"const\" solo se pueden usar en expresiones de acceso de propiedad o índice, o en la parte derecha de una declaración de importación, una asignación de exportación o una consulta de tipo.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "No se puede llamar a \"delete\" en un identificador en modo strict.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" solo se puede usar en un archivo .ts.", "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" solo se puede usar en un archivo .ts.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index e3a3fea1e6bb7..313315aa7b0be 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -12,11 +12,11 @@ "A_class_member_cannot_have_the_0_keyword_1248": "Un membre de classe ne peut pas avoir le mot clé '{0}'.", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Une expression avec virgule n'est pas autorisée dans un nom de propriété calculée.", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Un nom de propriété calculée ne peut pas référencer un paramètre de type à partir de son type conteneur.", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nom de propriété calculée dans une déclaration de propriété de classe doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nom de propriété calculée dans une surcharge de méthode doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nom de propriété calculée dans un littéral de type doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nom de propriété calculée dans un contexte ambiant doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nom de propriété calculée dans une interface doit faire référence à une expression dont le type est un type littéral ou un type 'symbole unique'.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Un nom de propriété calculée dans une déclaration de propriété de classe doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Un nom de propriété calculée dans une surcharge de méthode doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Un nom de propriété calculée dans un littéral de type doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Un nom de propriété calculée dans un contexte ambiant doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Un nom de propriété calculée dans une interface doit faire référence à une expression dont le type est un type littéral ou un type 'unique symbol'.", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Un nom de propriété calculée doit être de type 'string', 'number', 'symbol' ou 'any'.", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Un nom de propriété calculée de la forme '{0}' doit être de type 'symbol'.", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Un membre d'enum const n'est accessible qu'à l'aide d'un littéral de chaîne.", @@ -48,14 +48,15 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Une déclaration d'espace de noms ne peut pas se trouver dans un autre fichier que celui d'une classe ou d'une fonction avec laquelle elle est fusionnée.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Une déclaration d'espace de noms ne peut pas se trouver avant une classe ou une fonction avec laquelle elle est fusionnée.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Une déclaration d'espace de noms est autorisée uniquement dans un espace de noms ou un module.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Impossible d'appeler ou de construire une importation de style d'espace de noms, ce qui va entraîner un échec au moment de l'exécution.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un initialiseur de paramètre est uniquement autorisé dans une implémentation de fonction ou de constructeur.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Impossible de déclarer une propriété de paramètre à l'aide d'un paramètre rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Une propriété de paramètre est uniquement autorisée dans une implémentation de constructeur.", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Impossible de déclarer une propriété de paramètre à l'aide d'un modèle de liaison.", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Un chemin dans une option 'extends' doit être relatif ou rooté, mais '{0}' n'est ni l'un ni l'autre.", "A_promise_must_have_a_then_method_1059": "Une promesse doit avoir une méthode 'then'.", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Une propriété d'une classe dont le type est un type 'symbole unique' doit être à la fois 'static' et 'readonly'.", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Une propriété d'une interface ou d'un littéral de type dont le type est un type 'symbole unique' doit être 'readonly'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Une propriété d'une classe dont le type est un type 'unique symbol' doit être à la fois 'static' et 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Une propriété d'une interface ou d'un littéral de type dont le type est un type 'unique symbol' doit être 'readonly'.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Un paramètre obligatoire ne peut pas suivre un paramètre optionnel.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Un élément rest ne peut pas contenir de modèle de liaison.", "A_rest_element_cannot_have_an_initializer_1186": "Un élément rest ne peut pas avoir d'initialiseur.", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Un prédicat de type ne peut pas référencer un élément '{0}' dans un modèle de liaison.", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Un prédicat de type est autorisé uniquement dans une position de type de retour pour les fonctions et les méthodes.", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Le type d'un prédicat de type doit être assignable au type de son paramètre.", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Une variable dont le type est un type 'symbole unique' doit être 'const'.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Une variable dont le type est un type 'unique symbol' doit être 'const'.", "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.", @@ -91,11 +92,12 @@ "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.", - "Add_0_to_existing_import_declaration_from_1_90015": "Ajoutez '{0}' à une déclaration d'importation existante à partir de \"{1}\".", - "Add_index_signature_for_property_0_90017": "Ajoutez une signature d'index pour la propriété '{0}'.", - "Add_missing_super_call_90001": "Ajoutez l'appel manquant à 'super()'.", - "Add_this_to_unresolved_variable_90008": "Ajoutez 'this.' à la variable non résolue.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "L'ajout d'un fichier tsconfig.json permet d'organiser les projets qui contiennent des fichiers TypeScript et JavaScript. En savoir plus sur https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "Ajouter '{0}' à la déclaration d'importation existante de \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Ajouter le modificateur async dans la fonction conteneur", + "Add_index_signature_for_property_0_90017": "Ajouter une signature d'index pour la propriété '{0}'", + "Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'", + "Add_this_to_unresolved_variable_90008": "Ajouter 'this.' à la variable non résolue", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "L'ajout d'un fichier tsconfig.json permet d'organiser les projets qui contiennent des fichiers TypeScript et JavaScript. En savoir plus sur https://aka.ms/tsconfig.", "Additional_Checks_6176": "Vérifications supplémentaires", "Advanced_Options_6178": "Options avancées", "All_declarations_of_0_must_have_identical_modifiers_2687": "Toutes les déclarations de '{0}' doivent avoir des modificateurs identiques.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un paramètre de signature d'index ne peut pas avoir de modificateur d'accessibilité.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un paramètre de signature d'index ne peut pas avoir d'initialiseur.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un paramètre de signature d'index doit avoir une annotation de type.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un type de paramètre de signature d'index ne peut pas être un alias de type. Écrivez '[{0}: {1}]: {2}' à la place.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un type de paramètre de signature d'index ne peut pas être un type union. Utilisez un type d'objet mappé à la place.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Le type d'un paramètre de signature d'index doit être 'string' ou 'number'.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Une interface peut uniquement étendre un identificateur/nom qualifié avec des arguments de type facultatifs.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Une interface peut uniquement étendre une classe ou une autre interface.", @@ -165,7 +169,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_decorator_expression_90028": "Appeler 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}\"]' ?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Impossible d'importer les fichiers de déclaration de type. Importez '{0}' à la place de '{1}'.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Impossible d'initialiser la variable de portée externe '{0}' dans la même portée que celle de la déclaration de portée de bloc '{1}'.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Impossible d'appeler une expression dont le type n'a pas de signature d'appel. Le type '{0}' n'a aucune signature d'appel compatible.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Impossible d'appeler un objet qui a éventuellement une valeur 'null'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Impossible d'appeler un objet qui a éventuellement une valeur 'null' ou 'undefined'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Impossible d'appeler un objet qui a éventuellement une valeur 'undefined'.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Impossible de réexporter un type quand l'indicateur '--isolatedModules' est spécifié.", "Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "Changez 'extends' en 'implements'.", - "Change_spelling_to_0_90022": "Changez l'orthographe en '{0}'.", + "Change_0_to_1_90014": "Changer '{0}' en '{1}'", + "Change_extends_to_implements_90003": "Changer 'extends' en 'implements'", + "Change_spelling_to_0_90022": "Changer 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}'.", "Circular_definition_of_import_alias_0_2303": "Définition circulaire de l'alias d'importation '{0}'.", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Circularité détectée durant la résolution de la configuration : {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La classe '{0}' définit la fonction de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme propriété de membre d'instance.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' définit la propriété de membre d'instance '{1}', mais la classe étendue '{2}' le définit comme fonction de membre d'instance.", "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_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implémente de manière incorrecte la classe '{1}'. Voulez-vous vraiment étendre '{1}' et hériter de ses membres en tant que sous-classe ?", "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'.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Fichier conteneur non spécifié et répertoire racine impossible à déterminer. Recherche ignorée dans le dossier 'node_modules'.", "Convert_function_0_to_class_95002": "Convertir la fonction '{0}' en classe", "Convert_function_to_an_ES2015_class_95001": "Convertir la fonction en classe ES2015", + "Convert_to_ES6_module_95017": "Convertir en module ES6", "Convert_to_default_import_95013": "Convertir en importation par défaut", "Corrupted_locale_file_0_6051": "Fichier de paramètres régionaux endommagé : {0}.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Le fichier de déclaration du module '{0}' est introuvable. '{1}' a implicitement un type 'any'.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Déclaration attendue.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Le nom de la déclaration est en conflit avec l'identificateur global intégré '{0}'.", "Declaration_or_statement_expected_1128": "Déclaration ou instruction attendue.", - "Declare_method_0_90023": "Déclarez la méthode '{0}'.", - "Declare_property_0_90016": "Déclarez la propriété '{0}'.", - "Declare_static_method_0_90024": "Déclarez la méthode statique '{0}'.", - "Declare_static_property_0_90027": "Déclarez la propriété statique '{0}'.", + "Declare_method_0_90023": "Déclarer la méthode '{0}'", + "Declare_property_0_90016": "Déclarer la propriété '{0}'", + "Declare_static_method_0_90024": "Déclarer la méthode statique '{0}'", + "Declare_static_property_0_90027": "Déclarer la propriété statique '{0}'", "Decorators_are_not_valid_here_1206": "Les éléments décoratifs ne sont pas valides ici.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Impossible d'appliquer des éléments décoratifs à plusieurs accesseurs get/set du même nom.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'exportation par défaut du module a utilisé ou utilise le nom privé '{0}'.", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Déconseillé] Utilisez '--skipLibCheck' à la place. Permet d'ignorer le contrôle de type des fichiers de déclaration de la bibliothèque par défaut.", "Digit_expected_1124": "Chiffre attendu", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Le répertoire '{0}' n'existe pas. Toutes les recherches associées sont ignorées.", - "Disable_checking_for_this_file_90018": "Désactivez la vérification de ce fichier.", + "Disable_checking_for_this_file_90018": "Désactiver la vérification de ce fichier", "Disable_size_limitations_on_JavaScript_projects_6162": "Désactivez les limitations de taille sur les projets JavaScript.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Désactivez la vérification stricte des signatures génériques dans les types de fonction.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Interdisez les références dont la casse est incohérente dans le même fichier.", @@ -309,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Activez la vérification stricte de l'initialisation des propriétés dans les classes.", "Enable_strict_null_checks_6113": "Activez strict null checks.", "Enable_tracing_of_the_name_resolution_process_6085": "Activez le traçage du processus de résolution de noms.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Active l'interopérabilité entre les modules CommonJS et ES via la création d'objets d'espace de noms pour toutes les importations. Implique 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Active la prise en charge expérimentale des fonctions async ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Active la prise en charge expérimentale des éléments décoratifs ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Active la prise en charge expérimentale pour l'émission des métadonnées de type pour les éléments décoratifs.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Le nom de fichier '{0}' diffère du nom de fichier '{1}' déjà inclus uniquement par la casse.", "File_name_0_has_a_1_extension_stripping_it_6132": "Le nom de fichier '{0}' a une extension '{1}'. Suppression de l'extension.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La spécification de fichier ne peut pas contenir un répertoire parent ('..') après un caractère générique de répertoire récursif ('**') : '{0}'.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Une spécification de fichier ne peut pas contenir plusieurs caractères génériques de répertoires récursifs ('**') : '{0}'.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Une spécification de fichier ne peut pas se terminer par un caractère générique de répertoire récursif ('**') : '{0}'.", "Found_package_json_at_0_6099": "'package.json' trouvé sur '{0}'.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Les déclarations de fonction ne sont pas autorisées dans les blocs en mode strict durant le ciblage de la version 'ES3' ou 'ES5'.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Identificateur attendu. '{0}' est un mot réservé en mode strict. Les modules sont automatiquement en mode strict.", "Identifier_expected_1003": "Identificateur attendu.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificateur attendu. '__esModule' est réservé en tant que marqueur exporté durant la transformation des modules ECMAScript.", - "Ignore_this_error_message_90019": "Ignorez ce message d'erreur.", - "Implement_inherited_abstract_class_90007": "Implémentez la classe abstraite héritée.", - "Implement_interface_0_90006": "Implémentez l'interface '{0}'.", + "Ignore_this_error_message_90019": "Ignorer ce message d'erreur", + "Implement_inherited_abstract_class_90007": "Implémenter la classe abstraite héritée", + "Implement_interface_0_90006": "Implémenter l'interface '{0}'", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clause implements de la classe exportée '{0}' possède ou utilise le nom privé '{1}'.", - "Import_0_from_module_1_90013": "Importez '{0}' à partir du module \"{1}\".", + "Import_0_from_module_1_90013": "Importer '{0}' à partir du module \"{1}\"", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Vous ne pouvez pas utiliser l'assignation d'importation pour cibler des modules ECMAScript. Utilisez plutôt 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' ou un autre format de module.", "Import_declaration_0_is_using_private_name_1_4000": "La déclaration d'importation '{0}' utilise le nom privé '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La déclaration d'importation est en conflit avec la déclaration locale de '{0}'.", @@ -424,10 +433,10 @@ "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}'.", + "Infer_parameter_types_from_usage_95012": "Déduire les types des paramètres à partir de l'utilisation", + "Infer_type_of_0_from_usage_95011": "Déduire le type de '{0}' à partir de l'utilisation", + "Initialize_property_0_in_the_constructor_90020": "Initialiser la propriété '{0}' dans le constructeur", + "Initialize_static_property_0_90021": "Initialiser 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.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'initialiseur du paramètre '{0}' ne peut pas référencer l'identificateur '{1}' déclaré après lui.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'initialiseur ne fournit aucune valeur pour cet élément de liaison, et ce dernier n'a pas de valeur par défaut.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Les paramètres régionaux doivent être sous la forme ou -. Par exemple, '{0}' ou '{1}'.", "Longest_matching_prefix_for_0_is_1_6108": "Le préfixe correspondant le plus long pour '{0}' est '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Recherche dans le dossier 'node_modules', emplacement initial '{0}'.", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Faites de l'appel à 'super()' la première instruction du constructeur.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Faire de l'appel à 'super()' la première instruction du constructeur", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Le type d'objet mappé a implicitement un type de modèle 'any'.", "Member_0_implicitly_has_an_1_type_7008": "Le membre '{0}' possède implicitement un type '{1}'.", "Merge_conflict_marker_encountered_1185": "Marqueur de conflit de fusion rencontré.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La déclaration fusionnée '{0}' ne peut pas inclure de déclaration d'exportation par défaut. Ajoutez plutôt une déclaration 'export default {0}' distincte.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Le nom de module '{0}' a été correctement résolu en '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Le genre de résolution de module n'est pas spécifié. Utilisation de '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "Échec de la résolution de module à l'aide de 'rootDirs'.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Les séparateurs numériques consécutifs multiples ne sont pas autorisés.", "Multiple_constructor_implementations_are_not_allowed_2392": "Les implémentations de plusieurs constructeurs ne sont pas autorisées.", "NEWLINE_6061": "NOUVELLE LIGNE", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "La propriété nommée '{0}' des types '{1}' et '{2}' n'est pas identique.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'expression de classe non abstraite '{0}' n'implémente pas le membre abstrait hérité '{0}' de la classe '{1}'.", "Not_all_code_paths_return_a_value_7030": "Les chemins de code ne retournent pas tous une valeur.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Impossible d'assigner le type d'index numérique '{0}' au type d'index de chaîne '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "Les séparateurs numériques ne sont pas autorisés ici.", "Object_is_possibly_null_2531": "L'objet a peut-être la valeur 'null'.", "Object_is_possibly_null_or_undefined_2533": "L'objet a peut-être la valeur 'null' ou 'undefined'.", "Object_is_possibly_undefined_2532": "L'objet a peut-être la valeur 'undefined'.", @@ -526,7 +538,7 @@ "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "La propriété '{0}' du littéral d'objet possède implicitement un type '{1}'.", "Octal_digit_expected_1178": "Chiffre octal attendu.", "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "Les types de littéral octal doivent utiliser la syntaxe ES2015. Utilisez la syntaxe '{0}'.", - "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Les littéraux octaux ne sont pas autorisés dans l'initialiseur des membres d'énumérations. Utilisez la syntaxe '{0}'.", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Les littéraux octaux ne sont pas autorisés dans l'initialiseur des membres d'enums. Utilisez la syntaxe '{0}'.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Les littéraux octaux ne sont pas autorisés en mode strict.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Les littéraux octaux ne sont pas disponibles lorsque vous ciblez ECMAScript 5 et ultérieur. Utilisez la syntaxe '{0}'.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Une seule déclaration de variable est autorisée dans une instruction 'for...in'.", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Le type de paramètre du setter public '{0}' de la classe exportée porte ou utilise le nom privé '{1}'.", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analyser en mode strict et émettre \"use strict\" pour chaque fichier source.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Le modèle '{0}' ne peut avoir qu'un seul caractère '*' au maximum.", - "Prefix_0_with_an_underscore_90025": "Préfixez '{0}' avec un trait de soulignement.", + "Prefix_0_with_an_underscore_90025": "Faire précéder '{0}' d'un trait de soulignement", "Print_names_of_files_part_of_the_compilation_6155": "Imprimez les noms des fichiers faisant partie de la compilation.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Imprimez les noms des fichiers générés faisant partie de la compilation.", "Print_the_compiler_s_version_6019": "Affichez la version du compilateur.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propriété '{0}' n'a aucun initialiseur et n'est pas définitivement assignée dans le constructeur.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propriété '{0}' a implicitement le type 'any', car son accesseur get ne dispose pas d'une annotation de type de retour.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propriété '{0}' a implicitement le type 'any', car son accesseur set ne dispose pas d'une annotation de type de paramètre.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Impossible d'assigner la propriété '{0}' du type '{1}' à la même propriété du type de base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propriété '{0}' du type '{1}' ne peut pas être assignée au type '{2}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "La propriété '{0}' est déclarée mais sa valeur n'est jamais lue.", "Property_0_is_incompatible_with_index_signature_2530": "La propriété '{0}' est incompatible avec la signature d'index.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Lever une erreur sur les expressions et les déclarations ayant un type 'any' implicite.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Déclenche une erreur sur les expressions 'this' avec un type 'any' implicite.", "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", - "Remove_declaration_for_Colon_0_90004": "Supprimez la déclaration pour : '{0}'.", + "Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'", + "Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.", "Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Le type de retour de la méthode statique publique de la classe exportée possède ou utilise le nom privé '{0}'.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Réutilisation des résolutions de module provenant de '{0}', car les résolutions sont inchangées par rapport à l'ancien programme.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Réutilisation de la résolution du module '{0}' dans le fichier '{1}' à partir de l'ancien programme.", - "Rewrite_as_the_indexed_access_type_0_90026": "Réécrire en tant que type d'accès indexé '{0}'.", + "Rewrite_as_the_indexed_access_type_0_90026": "Réécrire en tant que type d'accès indexé '{0}'", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Impossible de déterminer le répertoire racine, chemins de recherche primaires ignorés.", "STRATEGY_6039": "STRATÉGIE", "Scoped_package_detected_looking_in_0_6182": "Package de portée détecté. Recherche dans '{0}'", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Options de mappage de source", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La signature de surcharge spécialisée n'est assignable à aucune signature non spécialisée.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Le spécificateur de l'importation dynamique ne peut pas être un élément spread.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Spécifiez la version cible d'ECMAScript : 'ES3' (par défaut), 'ES5', 'ES2015', 'ES2016', 'ES2017' ou 'ESNEXT'.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Spécifiez la version cible d'ECMAScript : 'ES3' (par défaut), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' ou 'ESNEXT'.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Spécifiez la génération de code JSX : 'preserve', 'react-native' ou 'react'.", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Spécifiez les fichiers bibliothèques à inclure dans la compilation : ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Spécifiez la génération de code du module : 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' ou 'ESNext'.", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Spécifiez le répertoire racine des fichiers d'entrée. Contrôlez la structure des répertoires de sortie avec --outDir.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'opérateur spread dans les expressions 'new' est disponible uniquement quand ECMAScript 5 ou version supérieure est ciblé.", "Spread_types_may_only_be_created_from_object_types_2698": "Vous ne pouvez créer des types Spread qu'à partir de types d'objet.", + "Starting_compilation_in_watch_mode_6031": "Démarrage de la compilation en mode espion...", "Statement_expected_1129": "Instruction attendue.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Les instructions ne sont pas autorisées dans les contextes ambiants.", "Static_members_cannot_reference_class_type_parameters_2302": "Les membres statiques ne peuvent pas référencer des paramètres de type de classe.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Littéral de chaîne attendu.", "String_literal_with_double_quotes_expected_1327": "Littéral de chaîne avec guillemets doubles attendu.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stylisez les erreurs et les messages avec de la couleur et du contexte (expérimental).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Les prochaines déclarations de propriétés doivent avoir le même type. La propriété '{0}' doit avoir le type '{1}', mais elle a ici le type '{2}'.", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Les déclarations de variable ultérieures doivent avoir le même type. La variable '{0}' doit être de type '{1}', mais elle a ici le type '{2}'.", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Le type de la substitution '{0}' du modèle '{1}' est incorrect. Attente de 'string'. Obtention de '{2}'.", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "La substitution '{0}' dans le modèle '{1}' ne peut avoir qu'un seul caractère '*' au maximum.", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Le type '{0}' n'est pas un type tableau ou un type chaîne, ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Le type '{0}' n'est pas un type tableau ou n'a pas de méthode '[Symbol.iterator]()' qui retourne un itérateur.", "Type_0_is_not_assignable_to_type_1_2322": "Impossible d'assigner le type '{0}' au type '{1}'.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Le type '{0}' ne peut pas être assigné au type '{1}'. Il existe deux types distincts portant ce nom, mais ils ne sont pas liés.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Impossible d'assigner le type '{0}' au type '{1}'. Il existe deux types distincts portant ce nom, mais ils ne sont pas liés.", "Type_0_is_not_comparable_to_type_1_2678": "Le type '{0}' n'est pas comparable au type '{1}'.", "Type_0_is_not_generic_2315": "Le type '{0}' n'est pas générique.", "Type_0_provides_no_match_for_the_signature_1_2658": "Le type '{0}' ne fournit aucune correspondance pour la signature '{1}'.", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Littéral de modèle inachevé.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Les appels de fonctions non typées ne peuvent pas accepter d'arguments de type.", "Unused_label_7028": "Étiquette inutilisée.", + "Use_synthetic_default_member_95016": "Utilisez un membre 'default' synthétique.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'utilisation d'une chaîne dans une instruction 'for...of' est prise en charge uniquement dans ECMAScript 5 et version supérieure.", "VERSION_6036": "VERSION", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "La valeur de type '{0}' n'a aucune propriété en commun avec le type '{1}'. Voulez-vous vraiment l'appeler ?", @@ -913,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Les déclarations 'const' doivent être initialisées.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'initialiseur de membre enum 'const' donne une valeur non finie.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'initialiseur de membre enum 'const' donne une valeur non autorisée 'NaN'.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Les enums 'const' ne peuvent être utilisés que dans les expressions d'accès à une propriété ou un index, ou dans la partie droite d'une déclaration d'importation ou d'une assignation d'exportation.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Les enums 'const' ne peuvent être utilisés que dans les expressions d'accès à une propriété ou un index, ou dans la partie droite d'une déclaration d'importation, d'une assignation d'exportation ou d'une requête de type.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' ne peut pas être appelé dans un identificateur en mode strict.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Les déclarations 'enum' peuvent uniquement être utilisées dans un fichier .ts.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' peut uniquement être utilisé dans un fichier .ts.", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Les 'expressions d'assertion de type' peuvent uniquement être utilisées dans un fichier .ts.", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Les 'déclarations de paramètre de type' peuvent uniquement être utilisées dans un fichier .ts.", "types_can_only_be_used_in_a_ts_file_8010": "Les 'types' peuvent uniquement être utilisés dans un fichier .ts.", - "unique_symbol_types_are_not_allowed_here_1335": "Les types 'symbole unique' ne sont pas autorisés ici.", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Les types 'symbole unique' sont uniquement autorisés sur les variables d'une déclaration de variable.", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Les types 'symbole unique' ne peuvent pas être utilisés dans une déclaration de variable avec un nom de liaison.", + "unique_symbol_types_are_not_allowed_here_1335": "Les types 'unique symbol' ne sont pas autorisés ici.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Les types 'unique symbol' sont uniquement autorisés sur les variables d'une déclaration de variable.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Les types 'unique symbol' ne peuvent pas être utilisés dans une déclaration de variable avec un nom de liaison.", "with_statements_are_not_allowed_in_an_async_function_block_1300": "Les instructions 'with' ne sont pas autorisées dans un bloc de fonctions async.", "with_statements_are_not_allowed_in_strict_mode_1101": "Les instructions 'with' ne sont pas autorisées en mode strict.", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Impossible d'utiliser des expressions 'yield' dans un initialiseur de paramètre." diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index a9fffd5450d9e..e52f44a50d3dc 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una dichiarazione di spazio dei nomi non può essere presente in un file diverso rispetto a una classe o funzione con cui è stato eseguito il merge.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una dichiarazione di spazio dei nomi non può essere specificata prima di una classe o funzione con cui è stato eseguito il merge.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una dichiarazione di spazio dei nomi è consentita solo in uno spazio dei nomi o in un modulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Non è possibile chiamare o costruire un'importazione in stile spazio dei nomi. Questo comporterà un errore in fase di runtime.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inizializzatore di parametro è consentito solo in un'implementazione di funzione o costruttore.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Non è possibile dichiarare una proprietà di parametro usando un parametro REST.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una proprietà di parametro è consentita solo in un'implementazione di costruttore.", @@ -91,11 +92,12 @@ "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.", - "Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\".", - "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'.", - "Add_missing_super_call_90001": "Aggiunge la chiamata mancante a 'super()'.", - "Add_this_to_unresolved_variable_90008": "Aggiungi 'this.' alla variabile non risolta.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Aggiungere un file tsconfig.json per organizzare più facilmente progetti che contengono sia file TypeScript che JavaScript. Per altre informazioni, vedere https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Aggiungere il modificatore async alla funzione contenitore", + "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'", + "Add_missing_super_call_90001": "Aggiungere la chiamata mancante a 'super()'", + "Add_this_to_unresolved_variable_90008": "Aggiungere 'this.' alla variabile non risolta", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Aggiungere un file tsconfig.json per organizzare più facilmente progetti che contengono sia file TypeScript che JavaScript. Per altre informazioni, vedere https://aka.ms/tsconfig.", "Additional_Checks_6176": "Controlli aggiuntivi", "Advanced_Options_6178": "Opzioni avanzate", "All_declarations_of_0_must_have_identical_modifiers_2687": "Tutte le dichiarazioni di '{0}' devono contenere modificatori identici.", @@ -111,12 +113,12 @@ "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Non è possibile dichiarare una funzione di accesso in un contesto di ambiente.", "An_accessor_cannot_have_type_parameters_1094": "Una funzione di accesso non può contenere parametri di tipo.", "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Una dichiarazione di modulo di ambiente è consentita solo al primo livello in un file.", - "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmetico deve essere di tipo 'any', 'number' o un tipo di enum.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Un operando aritmetico deve essere di tipo 'any', 'number' o un tipo di enumerazione.", "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Con una funzione o un metodo asincrono in ES5/ES3 è necessario il costruttore 'Promise'. Assicurarsi che sia presente una dichiarazione per il costruttore 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Una funzione o un metodo asincrono deve includere un tipo restituito awaitable valido.", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Un metodo o una funzione asincrona deve restituire un elemento 'Promise'. Assicurarsi che sia presente una dichiarazione per 'Promise' oppure includere 'ES2015' nell'opzione `--lib`.", "An_async_iterator_must_have_a_next_method_2519": "Un iteratore asincrono deve contenere un metodo 'next()'.", - "An_enum_member_cannot_have_a_numeric_name_2452": "Il nome di un membro enum non può essere numerico.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Il nome di un membro di enumerazione non può essere numerico.", "An_export_assignment_can_only_be_used_in_a_module_1231": "È possibile usare un'assegnazione di esportazione solo in un modulo.", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Non è possibile usare un'assegnazione di esportazione in un modulo con altri elementi esportati.", "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Non è possibile usare un'assegnazione di esportazione in uno spazio dei nomi.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parametro della firma dell'indice non può contenere un modificatore di accessibilità.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parametro della firma dell'indice non può contenere un inizializzatore.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parametro della firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un tipo di parametro della firma dell'indice non può essere un alias di tipo. Provare a scrivere '[{0}: {1}]: {2}'.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un tipo di parametro della firma dell'indice non può essere un tipo di unione. Provare a usare un tipo di oggetto con mapping.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Il tipo di un parametro della firma dell'indice deve essere 'string' o 'number'.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Un'interfaccia può estendere solo un identificatore/nome qualificato con argomenti tipo facoltativi.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Un'interfaccia può estendere solo una classe o un'altra interfaccia.", @@ -165,7 +169,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_decorator_expression_90028": "Chiamare 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}\"]'?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Non è possibile importare file di dichiarazione di tipo. Provare a importare '{0}' invece di '{1}'.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Non è possibile inizializzare la variabile con ambito esterna '{0}' nello stesso ambito della dichiarazione con ambito del blocco '{1}'.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Non è possibile richiamare un'espressione al cui tipo manca una firma di chiamata. Per il tipo '{0}' non esistono firme di chiamata compatibili.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Non è possibile richiamare un oggetto che è probabilmente 'null'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Non è possibile richiamare un oggetto che è probabilmente 'null' o 'undefined'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Non è possibile richiamare un oggetto che è probabilmente 'undefined'.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Non è possibile riesportare un tipo quando è stato specificato il flag '--isolatedModules'.", "Cannot_read_file_0_Colon_1_5012": "Non è possibile leggere il file '{0}': {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Non è possibile dichiarare di nuovo la variabile con ambito blocco '{0}'.", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "Cambia 'extends' in 'implements'.", - "Change_spelling_to_0_90022": "Modificare l'ortografia in '{0}'.", + "Change_0_to_1_90014": "Modificare '{0}' in '{1}'", + "Change_extends_to_implements_90003": "Cambiare '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}'.", "Circular_definition_of_import_alias_0_2303": "Definizione circolare dell'alias di importazione '{0}'.", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "È stata rilevata una circolarità durante la risoluzione della configurazione: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La classe '{0}' definisce '{1}' come funzione di membro di istanza, mentre la classe estesa '{2}' la definisce come proprietà di membro di istanza.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La classe '{0}' definisce '{1}' come proprietà di membro di istanza, mentre la classe estesa '{2}' la definisce come funzione di membro di istanza.", "Class_0_incorrectly_extends_base_class_1_2415": "La classe '{0}' estende in modo errato la classe di base '{1}'.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La classe '{0}' implementa in modo errato la classe '{1}'. Si intendeva estendere '{1}' ed ereditarne i membri come sottoclasse?", "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`.", @@ -230,7 +238,7 @@ "Classes_containing_abstract_methods_must_be_marked_abstract_2514": "Le classi che contengono metodi astratti devono essere contrassegnate come astratte.", "Command_line_Options_6171": "Opzioni della riga di comando", "Compilation_complete_Watching_for_file_changes_6042": "Compilazione completata. Verranno individuate le modifiche ai file.", - "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto di cui è stato specificato il percorso del file di configurazione o di una cartella contenente un file 'tsconfig.json'.", + "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto in base al percorso del file di configurazione o della cartella contenente un file 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "Con l'opzione '{0}' del compilatore è previsto un argomento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Con l'opzione '{0}' del compilatore è richiesto un valore di tipo {1}.", "Computed_property_names_are_not_allowed_in_enums_1164": "I nomi di proprietà calcolati non sono consentiti nelle enumerazioni.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Il file contenitore non è specificato e non è possibile determinare la directory radice. La ricerca nella cartella 'node_modules' verrà ignorata.", "Convert_function_0_to_class_95002": "Converti la funzione '{0}' in classe", "Convert_function_to_an_ES2015_class_95001": "Converti la funzione in una classe ES2015", + "Convert_to_ES6_module_95017": "Converti in modulo ES6", "Convert_to_default_import_95013": "Converti nell'importazione predefinita", "Corrupted_locale_file_0_6051": "Il file delle impostazioni locali {0} è danneggiato.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Non è stato trovato alcun file di dichiarazione per il modulo '{0}'. A '{1}' è assegnato implicitamente un tipo 'any'.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "È prevista la dichiarazione.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Il nome della dichiarazione è in conflitto con l'identificatore globale predefinito '{0}'.", "Declaration_or_statement_expected_1128": "È prevista la dichiarazione o l'istruzione.", - "Declare_method_0_90023": "Dichiarare il metodo '{0}'.", - "Declare_property_0_90016": "Dichiarare la proprietà '{0}'.", - "Declare_static_method_0_90024": "Dichiarare il metodo statico '{0}'.", - "Declare_static_property_0_90027": "Dichiarare la proprietà statica '{0}'.", + "Declare_method_0_90023": "Dichiarare il metodo '{0}'", + "Declare_property_0_90016": "Dichiarare la proprietà '{0}'", + "Declare_static_method_0_90024": "Dichiarare il metodo statico '{0}'", + "Declare_static_property_0_90027": "Dichiarare la proprietà statica '{0}'", "Decorators_are_not_valid_here_1206": "In questo punto le espressioni Decorator non sono valide.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Non è possibile applicare le espressioni Decorator a più funzioni di accesso get/set con lo stesso nome.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'esportazione predefinita del modulo contiene o usa il nome privato '{0}'.", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Deprecata] In alternativa, usare '--skipLibCheck'. Ignora il controllo del tipo dei file di dichiarazione delle librerie predefinite.", "Digit_expected_1124": "È prevista la cifra.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "La directory '{0}' non esiste. Tutte le ricerche che la interessano verranno ignorate.", - "Disable_checking_for_this_file_90018": "Disabilita la verifica per questo file.", + "Disable_checking_for_this_file_90018": "Disabilitare la verifica per questo file", "Disable_size_limitations_on_JavaScript_projects_6162": "Disabilita le dimensioni relative alle dimensioni per i progetti JavaScript.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Disabilitare il controllo tassativo delle firme generiche nei tipi funzione.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Non consente riferimenti allo stesso file in cui le maiuscole/minuscole vengono usate in modo incoerente.", @@ -275,7 +284,7 @@ "Do_not_emit_outputs_6010": "Non crea output.", "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Non crea output se sono stati restituiti errori.", "Do_not_emit_use_strict_directives_in_module_output_6112": "Non crea direttive 'use strict' nell'output del modulo.", - "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Non cancella le dichiarazioni enum const nel codice generato.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Non cancella le dichiarazioni di enumerazione const nel codice generato.", "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Non genera funzioni di supporto personalizzate, come '__extends', nell'output compilato.", "Do_not_include_the_default_library_file_lib_d_ts_6158": "Non include il file di libreria predefinito (lib.d.ts).", "Do_not_report_errors_on_unreachable_code_6077": "Non segnala gli errori in caso di codice non raggiungibile.", @@ -302,20 +311,21 @@ "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "L'elemento contiene implicitamente un tipo 'any' perché l'espressione di indice non è di tipo 'number'.", "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "L'elemento contiene implicitamente un tipo 'any' perché al tipo '{0}' non è assegnata alcuna firma dell'indice.", "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "Crea un BOM (Byte Order Mark) UTF-8 all'inizio dei file di output.", - "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping d origine invece di file separati.", + "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "Crea un unico file con i mapping di origine invece di file separati.", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "Crea l'origine unitamente alle mappe di origine all'interno di un unico file. Richiede l'impostazione di '--inlineSourceMap' o '--sourceMap'.", "Enable_all_strict_type_checking_options_6180": "Abilita tutte le opzioni per i controlli del tipo strict.", - "Enable_strict_checking_of_function_types_6186": "Abilitare il controllo tassativo dei tipi funzione.", + "Enable_strict_checking_of_function_types_6186": "Abilita il controllo tassativo dei tipi funzione.", "Enable_strict_checking_of_property_initialization_in_classes_6187": "Abilita il controllo tassativo dell'inizializzazione delle proprietà nelle classi.", "Enable_strict_null_checks_6113": "Abilita i controlli strict Null.", "Enable_tracing_of_the_name_resolution_process_6085": "Abilita la traccia del processo di risoluzione dei nomi.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Abilita l'interoperabilità di creazione tra moduli ES e CommonJS tramite la creazione di oggetti spazio dei nomi per tutte le importazioni. Implica 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Abilita il supporto sperimentale per le funzioni asincrone di ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Abilita il supporto sperimentale per le espressioni Decorator di ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Abilita il supporto sperimentale per la creazione dei metadati dei tipi per le espressioni Decorator.", "Enum_0_used_before_its_declaration_2450": "L'enumerazione '{0}' è stata usata prima di essere stata dichiarata.", - "Enum_declarations_must_all_be_const_or_non_const_2473": "Le dichiarazioni enum devono essere tutte const o tutte non const.", - "Enum_member_expected_1132": "È previsto il membro enum.", - "Enum_member_must_have_initializer_1061": "Il membro enum deve contenere l'inizializzatore.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Le dichiarazioni di enumerazione devono essere tutte const o tutte non const.", + "Enum_member_expected_1132": "È previsto il membro di enumerazione.", + "Enum_member_must_have_initializer_1061": "Il membro di enumerazione deve contenere l'inizializzatore.", "Enum_name_cannot_be_0_2431": "Il nome dell'enumerazione non può essere '{0}'.", "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Il tipo di enumerazione '{0}' contiene membri i cui inizializzatori non sono valori letterali.", "Examples_Colon_0_6026": "Esempi: {0}", @@ -324,9 +334,9 @@ "Expected_0_arguments_but_got_1_2554": "Sono previsti {0} argomenti, ma ne sono stati ottenuti {1}.", "Expected_0_arguments_but_got_1_or_more_2556": "Sono previsti {0} argomenti, ma ne sono stati ottenuti più di {1}.", "Expected_0_type_arguments_but_got_1_2558": "Sono previsti {0} argomenti tipo, ma ne sono stati ottenuti {1}.", - "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Sono previsti argomento tipo {0}. Per specificarli, usare un tag '@extends'.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Sono previsti {0} argomenti tipo. Per specificarli, usare un tag '@extends'.", "Expected_at_least_0_arguments_but_got_1_2555": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti {1}.", - "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti più di {1}.", + "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Sono previsti almeno {0} argomenti, ma ne sono stati ottenuti {1} o più.", "Expected_corresponding_JSX_closing_tag_for_0_17002": "È previsto il tag di chiusura JSX corrispondente per '{0}'.", "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "È previsto il tag di chiusura corrispondente per il frammento JSX.", "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105": "Il tipo previsto del campo '{0}' in 'package.json' è 'string', ma è stato ottenuto '{1}'.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Il nome file '{0}' differisce da quello già incluso '{1}' solo per l'uso di maiuscole/minuscole.", "File_name_0_has_a_1_extension_stripping_it_6132": "L'estensione del nome file '{0}' è '{1}' e verrà rimossa.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "La specifica del file non può contenere una directory padre ('..') inserita dopo un carattere jolly ('**') di directory ricorsiva: '{0}'.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "La specifica del file non può contenere più caratteri jolly ('**') di directory ricorsiva: '{0}'.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "La specifica del file non può terminare con caratteri jolly ('**') di directory ricorsiva: '{0}'.", "Found_package_json_at_0_6099": "Il file 'package.json' è stato trovato in '{0}'.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Le dichiarazioni di funzione non sono consentite all'interno di blocchi in modalità strict quando la destinazione è 'ES3' o 'ES5'.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "È previsto un identificatore. '{0}' è una parola riservata in modalità strict. I moduli vengono impostati automaticamente in modalità strict.", "Identifier_expected_1003": "È previsto l'identificatore.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "È previsto un identificatore. '__esModule' è riservato come marcatore esportato durante la trasformazione di moduli ECMAScript.", - "Ignore_this_error_message_90019": "Ignora questo messaggio di errore.", - "Implement_inherited_abstract_class_90007": "Implementa la classe astratta ereditata.", - "Implement_interface_0_90006": "Implementa l'interfaccia '{0}'.", + "Ignore_this_error_message_90019": "Ignorare questo messaggio di errore", + "Implement_inherited_abstract_class_90007": "Implementare la classe astratta ereditata", + "Implement_interface_0_90006": "Implementare l'interfaccia '{0}'", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "La clausola implements della classe esportata '{0}' contiene o usa il nome privato '{1}'.", - "Import_0_from_module_1_90013": "Importa '{0}' dal modulo \"{1}\".", + "Import_0_from_module_1_90013": "Importare '{0}' dal modulo \"{1}\"", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Non è possibile usare l'assegnazione di importazione se destinata a moduli ECMAScript. Provare a usare 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' o un altro formato di modulo.", "Import_declaration_0_is_using_private_name_1_4000": "La dichiarazione di importazione '{0}' usa il nome privato '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La dichiarazione di importazione è in conflitto con la dichiarazione locale di '{0}'.", @@ -417,17 +426,17 @@ "Import_name_cannot_be_0_2438": "Il nome dell'importazione non può essere '{0}'.", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La dichiarazione di importazione o esportazione in una dichiarazione di modulo di ambiente non può fare riferimento al modulo tramite il nome di modulo relativo.", "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Le importazioni non sono consentite negli aumenti di modulo. Provare a spostarle nel modulo esterno di inclusione.", - "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Nelle dichiarazioni enum dell'ambiente l'inizializzatore di membro deve essere un'espressione costante.", - "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In un'enumerazione con più dichiarazioni solo una di queste può omettere un inizializzatore per il primo elemento enum.", - "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Nelle dichiarazioni enum 'const' l'inizializzatore di membro deve essere un'espressione costante.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Nelle dichiarazioni di enumerazione dell'ambiente l'inizializzatore di membro deve essere un'espressione costante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "In un'enumerazione con più dichiarazioni solo una di queste può omettere un inizializzatore per il primo elemento dell'enumerazione.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Nelle dichiarazioni di enumerazione 'const' l'inizializzatore di membro deve essere un'espressione costante.", "Index_signature_in_type_0_only_permits_reading_2542": "La firma dell'indice nel tipo '{0}' consente solo la lettura.", "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}'.", + "Infer_parameter_types_from_usage_95012": "Derivare i tipi di parametro dall'utilizzo", + "Infer_type_of_0_from_usage_95011": "Derivare il tipo di '{0}' dall'utilizzo", + "Initialize_property_0_in_the_constructor_90020": "Inizializzare la proprietà '{0}' nel costruttore", + "Initialize_static_property_0_90021": "Inizializzare 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.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'inizializzatore del parametro '{0}' non può fare riferimento all'identificatore '{1}' dichiarato dopo di esso.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'inizializzatore non fornisce alcun valore per questo elemento di binding e per quest'ultimo non è disponibile un valore predefinito.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Le impostazioni locali devono essere nel formato o -, ad esempio, '{0}' o '{1}'.", "Longest_matching_prefix_for_0_is_1_6108": "Il prefisso di corrispondenza più lungo per '{0}' è '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Verrà eseguita la ricerca nella cartella 'node_modules'. Percorso iniziale: '{0}'.", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Imposta la chiamata a 'super()' come prima istruzione nel costruttore.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Impostare la chiamata a 'super()' come prima istruzione nel costruttore", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Il tipo di oggetto con mapping contiene implicitamente un tipo di modello 'any'.", "Member_0_implicitly_has_an_1_type_7008": "Il membro '{0}' contiene implicitamente un tipo '{1}'.", "Merge_conflict_marker_encountered_1185": "È stato rilevato un indicatore di conflitti di merge.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La dichiarazione '{0}' sottoposta a merge non può includere una dichiarazione di esportazione predefinita. Provare ad aggiungere una dichiarazione 'export default {0}' distinta.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Il nome del modulo '{0}' è stato risolto in '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Il tipo di risoluzione del modulo non è specificato. Verrà usato '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "La risoluzione del modulo con 'rootDirs' non è riuscita.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Non sono consentiti più separatori numerici consecutivi.", "Multiple_constructor_implementations_are_not_allowed_2392": "Non è possibile usare più implementazioni di costruttore.", "NEWLINE_6061": "NUOVA RIGA", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Le proprietà denominate '{0}' dei tipi '{1}' e '{2}' non sono identiche.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'espressione di classe non astratta non implementa il membro astratto ereditato '{0}' dalla classe '{1}'.", "Not_all_code_paths_return_a_value_7030": "Non tutti i percorsi del codice restituiscono un valore.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Il tipo di indice numerico '{0}' non è assegnabile al tipo di indice stringa '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "I separatori numerici non sono consentiti in questa posizione.", "Object_is_possibly_null_2531": "L'oggetto è probabilmente 'null'.", "Object_is_possibly_null_or_undefined_2533": "L'oggetto è probabilmente 'null' o 'undefined'.", "Object_is_possibly_undefined_2532": "L'oggetto è probabilmente 'undefined'.", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Il tipo di parametro del setter statico pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Esegue l'analisi in modalità strict e crea la direttiva \"use strict\" per ogni file di origine.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Il criterio '{0}' deve contenere al massimo un carattere '*'.", - "Prefix_0_with_an_underscore_90025": "Anteporre un carattere di sottolineatura a '{0}'.", + "Prefix_0_with_an_underscore_90025": "Anteporre un carattere di sottolineatura a '{0}'", "Print_names_of_files_part_of_the_compilation_6155": "Stampa i nomi dei file che fanno parte della compilazione.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Stampa i nomi dei file generati che fanno parte della compilazione.", "Print_the_compiler_s_version_6019": "Stampa la versione del compilatore.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata nel costruttore.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso get manca un'annotazione di tipo restituito.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso set manca un'annotazione di tipo di parametro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La proprietà '{0}' nel tipo '{1}' non è assegnabile alla stessa proprietà nel tipo di base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La proprietà '{0}' nel tipo '{1}' non è assegnabile al tipo '{2}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "La proprietà '{0}' è dichiarata, ma il suo valore non viene mai letto.", "Property_0_is_incompatible_with_index_signature_2530": "La proprietà '{0}' non è compatibile con la firma dell'indice.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Genera un errore in caso di espressioni o dichiarazioni con tipo 'any' implicito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Genera un errore in caso di espressioni 'this con un tipo 'any' implicito.", "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", - "Remove_declaration_for_Colon_0_90004": "Rimuovi la dichiarazione per {0}.", + "Remove_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione per '{0}'", + "Replace_import_with_0_95015": "Sostituire l'importazione con '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Segnala l'errore quando non tutti i percorsi del codice nella funzione restituiscono un valore.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Segnala errori per i casi di fallthrough nell'istruzione switch.", "Report_errors_in_js_files_8019": "Segnala gli errori presenti nei file con estensione js.", @@ -674,13 +688,13 @@ "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Il tipo restituito del metodo pubblico della classe esportata contiene o usa il nome privato '{0}'.", "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo esterno '{2}', ma non può essere rinominato.", "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome '{1}' del modulo privato '{2}'.", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Il tipo restituito del getter di proprietà pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Il tipo restituito del getter statico pubblico '{0}' della classe esportata contiene o usa il nome privato '{1}'.", "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo esterno {1} ma non può essere rinominato.", "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome '{0}' del modulo privato '{1}'.", "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Il tipo restituito del metodo statico pubblico della classe esportata contiene o usa il nome privato '{0}'.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Le risoluzioni dei moduli con origine in '{0}' verranno riutilizzate perché sono invariate rispetto al vecchio programma.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "La risoluzione del modulo '{0}' del vecchio programma verrà riutilizzata nel file '{1}'.", - "Rewrite_as_the_indexed_access_type_0_90026": "Riscrivere come tipo di accesso indicizzato '{0}'.", + "Rewrite_as_the_indexed_access_type_0_90026": "Riscrivere come tipo di accesso indicizzato '{0}'", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Non è possibile determinare la directory radice. I percorsi di ricerca primaria verranno ignorati.", "STRATEGY_6039": "STRATEGIA", "Scoped_package_detected_looking_in_0_6182": "Il pacchetto con ambito è stato rilevato. Verrà eseguita una ricerca in '{0}'", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Opzioni per mapping di origine", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "La firma di overload specializzata non è assegnabile a una firma non specializzata.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "L'identificatore dell'importazione dinamica non può essere l'elemento spread.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Specifica la versione di destinazione di ECMAScript: 'ES3' (predefinita), 'ES5', 'ES2015', 'ES2016', 'ES2017' o 'ESNEXT'.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Specificare la versione di destinazione di ECMAScript: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' o 'ESNEXT'.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Specifica la generazione del codice JSX: 'preserve', 'react-native' o 'react'.", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Specifica i file di libreria da includere nella compilazione: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Consente di specificare il tipo di generazione del codice del modulo, ovvero 'none', commonjs', 'amd', 'system', 'umd', 'es2015' o 'ESNext'.", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Specifica la directory radice dei file di input. Usare per controllare la struttura della directory di output con --outDir.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "L'operatore Spread in espressioni 'new' è disponibile solo se destinato a ECMAScript 5 e versioni successive.", "Spread_types_may_only_be_created_from_object_types_2698": "È possibile creare tipi spread solo da tipi di oggetto.", + "Starting_compilation_in_watch_mode_6031": "Avvio della compilazione in modalità espressione di controllo...", "Statement_expected_1129": "È prevista l'istruzione.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Le istruzioni non sono consentite in contesti di ambiente.", "Static_members_cannot_reference_class_type_parameters_2302": "I membri statici non possono fare riferimento a parametri di tipo classe.", @@ -765,7 +780,7 @@ "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte destra di un'espressione 'instanceof' deve essere di tipo 'any' o di un tipo assegnabile al tipo di interfaccia 'Function'.", "The_specified_path_does_not_exist_Colon_0_5058": "Il percorso specificato non esiste: '{0}'.", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "La destinazione di un'assegnazione deve essere una variabile o un accesso a proprietà.", - "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La destinazione di un'assegnazione rimanente dell'oggetto deve essere una variabile o un accesso a proprietà.", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "La destinazione di un'assegnazione REST di oggetto deve essere una variabile o un accesso a proprietà.", "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "Il contesto 'this' del tipo '{0}' non è assegnabile a quello 'this' di tipo '{1}' del metodo.", "The_this_types_of_each_signature_are_incompatible_2685": "I tipi 'this' delle singole firme non sono compatibili.", "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "Non è possibile dedurre l'argomento tipo per il parametro di tipo '{0}' dall'utilizzo. Provare a specificare gli argomenti tipo in modo esplicito.", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Il tipo '{0}' non è un tipo matrice o stringa oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Il tipo '{0}' non è un tipo matrice oppure non contiene un metodo '[Symbol.iterator]()' che restituisce un iteratore.", "Type_0_is_not_assignable_to_type_1_2322": "Il tipo '{0}' non è assegnabile al tipo '{1}'.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Il tipo '{0}' non è assegnabile al tipo '{1}'. Sono presenti due tipi diversi con questo nome, che però non sono correlati.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Il tipo '{0}' non è assegnabile al tipo '{1}'. Sono presenti due tipi diversi con questo nome, che però non sono correlati.", "Type_0_is_not_comparable_to_type_1_2678": "Il tipo '{0}' non è confrontabile con il tipo '{1}'.", "Type_0_is_not_generic_2315": "Il tipo '{0}' non è generico.", "Type_0_provides_no_match_for_the_signature_1_2658": "Il tipo '{0}' non fornisce corrispondenze per la firma '{1}'.", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Valore letterale di modello senza terminazione.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Le chiamate di funzione non tipizzate potrebbero non accettare argomenti tipo.", "Unused_label_7028": "Etichetta non usata.", + "Use_synthetic_default_member_95016": "Usare il membro 'default' sintetico.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", "VERSION_6036": "VERSIONE", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Il valore di tipo '{0}' non ha proprietà in comune con il tipo '{1}'. Si intendeva chiamarlo?", @@ -911,9 +927,9 @@ "class_expressions_are_not_currently_supported_9003": "Le espressioni 'class' non sono attualmente supportate.", "const_declarations_can_only_be_declared_inside_a_block_1156": "Le dichiarazioni 'const' possono essere dichiarate solo all'interno di un blocco.", "const_declarations_must_be_initialized_1155": "Le dichiarazioni 'const' devono essere inizializzate.", - "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'inizializzatore di membro enum 'const' è stato valutato come valore non finito.", - "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'inizializzatore di membro enum 'const' è stato valutato come valore non consentito 'NaN'.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Le enumerazioni 'const' possono essere usate solo in espressioni di accesso a proprietà o indice oppure nella parte destra di un'assegnazione di esportazione o di una dichiarazione di importazione.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non consentito 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Le enumerazioni 'const' possono essere usate solo in espressioni di accesso a proprietà o indice oppure nella parte destra di un'assegnazione di esportazione, di una dichiarazione di importazione o di una query su tipo.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Non è possibile chiamare 'delete' su un identificatore in modalità strict.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' può essere usato solo in un file con estensione ts.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' può essere usato solo in un file con estensione ts.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 45d39e6d00b3b..a02d6e57d7e05 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -12,11 +12,11 @@ "A_class_member_cannot_have_the_0_keyword_1248": "クラス メンバーに '{0}' キーワードを指定することはできません。", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "コンマ式は計算されたプロパティ名では使用できません。", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "計算されたプロパティ名は、型パラメーターをそれを含む型から参照することはできません。", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "クラス プロパティ宣言内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "メソッド オーバーロード内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "型リテラル内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境コンテキスト内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "インターフェイス内の計算されたプロパティ名は、型がリテラル型または '一意のシンボル' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "クラス プロパティ宣言内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "メソッド オーバーロード内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "型リテラル内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境コンテキスト内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "インターフェイス内の計算されたプロパティ名は、型がリテラル型または 'unique symbol' 型の式を参照する必要があります。", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "計算されたプロパティ名は 'string' 型、'number' 型、'symbol' 型、または 'any' 型のいずれかでなければなりません。", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "形式 '{0}' の計算されたプロパティ名は 'symbol' 型でなければなりません。", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 列挙型メンバーは、文字列リテラルを使用してのみアクセスできます。", @@ -42,20 +42,21 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "ジェネレーターに 'void' 型の注釈を指定することはできません。", "A_get_accessor_cannot_have_parameters_1054": "'get' アクセサーにパラメーターを指定することはできません。", "A_get_accessor_must_return_a_value_2378": "'get' アクセサーは値を返す必要があります。", - "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "enum 宣言のメンバー初期化子は、他の enum で定義されたメンバーを含め、その後で宣言されたメンバーを参照できません。", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "列挙型宣言のメンバー初期化子は、他の列挙型で定義されたメンバーを含め、その後で宣言されたメンバーを参照できません。", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin クラスには、型 'any[]' の単一の rest パラメーターを持つコンストラクターが必要です。", "A_module_cannot_have_multiple_default_exports_2528": "モジュールに複数の既定のエクスポートを含めることはできません。", "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "名前空間宣言は、それとマージするクラスや関数と異なるファイルに配置できません。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "名前空間宣言は、それとマージするクラスや関数より前に配置できません。", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "名前空間宣言は、名前空間かモジュールでのみ使用できます。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "名前空間スタイルのインポートを呼び出したり、構築したりすることはできません。実行時にエラーが発生する原因となります。", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "パラメーター初期化子は、関数またはコンストラクターの実装でのみ指定できます。", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "パラメーター プロパティは、rest パラメーターを使用して宣言することはできません。", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "パラメーター プロパティは、コンストラクターの実装でのみ指定できます。", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "パラメーター プロパティは、バインド パターンを使用して宣言することはできません。", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'拡張' オプション内のパスは相対パスまたはルート パスである必要がありますが、'{0}' の場合は、その必要はありません。", "A_promise_must_have_a_then_method_1059": "Promise には 'then' メソッドが必要です。", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "型が '一意のシンボル' 型のクラスのプロパティは、'static' と 'readonly' の両方である必要があります。", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "型が '一意のシンボル' 型のインターフェイスまたは型リテラルのプロパティは、'readonly' である必要があります。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "型が 'unique symbol' 型のクラスのプロパティは、'static' と 'readonly' の両方である必要があります。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "型が 'unique symbol' 型のインターフェイスまたは型リテラルのプロパティは、'readonly' である必要があります。", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必須パラメーターを省略可能なパラメーターの後に指定することはできません。", "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 要素にバインド パターンを含めることはできません。", "A_rest_element_cannot_have_an_initializer_1186": "rest 要素に初期化子を指定することはできません。", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "型の述語は、バインド パターン内の要素 '{0}' を参照できません。", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "型の述語は、関数およびメソッドの戻り値の型の位置でのみ使用できます。", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "type 述語の型はそのパラメーターの型に割り当て可能である必要があります。", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "型が '一意のシンボル' 型の変数は、'const' である必要があります。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "型が 'unique symbol' 型の変数は、'const' である必要があります。", "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": "抽象メソッドは抽象クラス内でのみ使用できます。", @@ -91,11 +92,12 @@ "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": "アクセサーはどちらも抽象または非抽象である必要があります。", - "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\" から既存のインポート宣言に '{0}' を追加します。", - "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加します。", - "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加します。", - "Add_this_to_unresolved_variable_90008": "'this.' を未解決の変数に追加します。", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "tsconfig.json ファイルを追加すると、TypeScript ファイルと JavaScript ファイルの両方を含むプロジェクトを整理できます。詳細については、https://aka.ms/tsconfig をご覧ください。", + "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\" から既存のインポート宣言に '{0}' を追加する", + "Add_async_modifier_to_containing_function_90029": "含まれている関数に async 修飾子を追加します", + "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する", + "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加する", + "Add_this_to_unresolved_variable_90008": "'this.' を未解決の変数に追加する", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json ファイルを追加すると、TypeScript ファイルと JavaScript ファイルの両方を含むプロジェクトを整理できます。詳細については、https://aka.ms/tsconfig をご覧ください。", "Additional_Checks_6176": "追加のチェック", "Advanced_Options_6178": "詳細オプション", "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' のすべての宣言には、同一の修飾子が必要です。", @@ -116,7 +118,7 @@ "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "非同期関数または非同期メソッドには、有効で待機可能な戻り値の型を指定する必要があります。", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "非同期関数またはメソッドは 'Promise' を返す必要があります。'Promise' の宣言があること、または `--lib` オプションに 'ES2015' を含めていることを確認してください。", "An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。", - "An_enum_member_cannot_have_a_numeric_name_2452": "列挙メンバーに数値名を含めることはできません。", + "An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。", "An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。", "An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの割り当ては、名前空間では使用できません。", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "インデックス シグネチャのパラメーターにアクセシビリティ修飾子を指定することはできません。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "インデックス シグネチャのパラメーターに初期化子を指定することはできません。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "インデックス シグネチャのパラメーターには型の注釈が必要です。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "インデックス シグネチャのパラメーターの型を型のエイリアスにすることはできません。代わりに、'[{0}: {1}]: {2}' と記述することをご検討ください。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "インデックス シグネチャのパラメーターの型を共用体型にすることはできません。代わりに、マップされたオブジェクト型の使用をご検討ください。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "インデックス シグネチャのパラメーターの型は 'string' または 'number' でなければなりません。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "インターフェイスが拡張するのは、オプションの型引数が指定された識別子/完全修飾名のみです。", "An_interface_may_only_extend_a_class_or_another_interface_2312": "インターフェイスで拡張できるのは、クラスまたは他のインターフェイスのみです。", @@ -165,7 +169,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_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}' の型を取得するつもりでしたか?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "型宣言ファイルをインポートできません。'{1}' の代わりに '{0}' をインポートすることを検討してください。", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "ブロック スコープ宣言 '{1}' と同じスコープ内の外部スコープ変数 '{0}' を初期化できません。", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "型に呼び出しシグネチャがない式を呼び出すことはできません。型 '{0}' には互換性のある呼び出しシグネチャがありません。", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null' または 'undefined' の可能性があるオブジェクトを呼び出すことはできません。", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'undefined' の可能性があるオブジェクトを呼び出すことはできません。", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "0'--isolatedModules' フラグが指定されている場合、型を再エクスポートできません。", "Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "'extends' を 'implements' に変更します。", - "Change_spelling_to_0_90022": "スペルを '{0}' に変更してください。", + "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}' の最長一致のプレフィックスであるかを確認しています。", "Circular_definition_of_import_alias_0_2303": "インポート エイリアス '{0}' の循環定義です。", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "構成: {0} の解決中に循環が検出されました", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "クラス '{0}' で定義されたインスタンス メンバー関数 '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー プロパティとして定義されています。", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "クラス '{0}' で定義されたインスタンス メンバー プロパティ '{1}' が、拡張されたクラス '{2}' ではインスタンス メンバー関数として定義されています。", "Class_0_incorrectly_extends_base_class_1_2415": "クラス '{0}' は基底クラス '{1}' を正しく拡張していません。", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "クラス '{0}' はクラス '{1}' を正しく実装していません。'{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` タグを使用することはできません。", @@ -233,8 +241,8 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。", "Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。", "Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。", - "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙では使用できません。", - "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙では、計算値は許可されません。", + "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙型では使用できません。", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "文字列値のメンバーを持つ列挙型では、計算値は許可されません。", "Concatenate_and_emit_output_to_single_file_6001": "出力を連結して 1 つのファイルを生成します。", "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{0}' の定義が '{1}' および '{2}' で競合しています。競合を解決するには、このライブラリの特定バージョンのインストールをご検討ください。", "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "戻り値の型の注釈がないコンストラクト シグネチャの戻り値の型は、暗黙的に 'any' になります。", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。", "Convert_function_0_to_class_95002": "関数 '{0}' をクラスに変換します", "Convert_function_to_an_ES2015_class_95001": "関数を ES2015 クラスに変換します", + "Convert_to_ES6_module_95017": "ES6 モジュールに変換します", "Convert_to_default_import_95013": "既定のインポートに変換する", "Corrupted_locale_file_0_6051": "ロケール ファイル {0} は破損しています。", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "モジュール '{0}' の宣言ファイルが見つかりませんでした。'{1}' は暗黙的に 'any' 型になります。", @@ -253,19 +262,19 @@ "Declaration_expected_1146": "宣言が必要です。", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "宣言名が組み込みのグローバル識別子 '{0}' と競合しています。", "Declaration_or_statement_expected_1128": "宣言またはステートメントが必要です。", - "Declare_method_0_90023": "メソッド '{0}' を宣言します。", - "Declare_property_0_90016": "プロパティ '{0}' を宣言します。", - "Declare_static_method_0_90024": "静的メソッド '{0}' を宣言します。", - "Declare_static_property_0_90027": "静的プロパティ '{0}' を宣言します。", + "Declare_method_0_90023": "メソッド '{0}' を宣言する", + "Declare_property_0_90016": "プロパティ '{0}' を宣言する", + "Declare_static_method_0_90024": "静的メソッド '{0}' を宣言する", + "Declare_static_property_0_90027": "静的プロパティ '{0}' を宣言する", "Decorators_are_not_valid_here_1206": "デコレーターはここでは無効です。", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "デコレーターを同じ名前の複数の get/set アクセサーに適用することはできません。", - "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "モジュールの既定エクスポートがプライベート名 '{0}' を使用しています。", + "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "モジュールの既定エクスポートがプライベート名 '{0}' を持っているか、使用しています。", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[非推奨] 代わりに '--jsxFactory' を使います。'react' JSX 発行を対象とするときに、createElement に対して呼び出されたオブジェクトを指定します", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[非推奨] 代わりに '--outFile' を使います。出力を連結して 1 つのファイルを生成します", "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[非推奨] 代わりに '--skipLibCheck' を使います。既定のライブラリ宣言ファイルの型チェックをスキップします。", "Digit_expected_1124": "数値が必要です", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "ディレクトリ '{0}' は存在していません。ディレクトリ内のすべての参照をスキップしています。", - "Disable_checking_for_this_file_90018": "このファイルのチェックを無効にします。", + "Disable_checking_for_this_file_90018": "このファイルのチェックを無効にする", "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript プロジェクトのサイズ制限を無効にします。", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "関数型の汎用シグネチャに対する厳密なチェックを無効にします。", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "同じファイルへの大文字小文字の異なる参照を許可しない。", @@ -275,7 +284,7 @@ "Do_not_emit_outputs_6010": "出力しないでください。", "Do_not_emit_outputs_if_any_errors_were_reported_6008": "エラーが報告される場合は、出力しないでください。", "Do_not_emit_use_strict_directives_in_module_output_6112": "モジュール出力で 'use strict' ディレクティブを生成しません。", - "Do_not_erase_const_enum_declarations_in_generated_code_6007": "生成されたコード内で const enum 宣言を消去しないでください。", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "生成されたコード内で const 列挙型宣言を消去しないでください。", "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "コンパイルされた出力で '__extends' などのカスタム ヘルパー関数を生成しないでください。", "Do_not_include_the_default_library_file_lib_d_ts_6158": "既定のライブラリ ファイル (lib.d.ts) を含めないでください。", "Do_not_report_errors_on_unreachable_code_6077": "到達できないコードに関するエラーを報告しない。", @@ -304,18 +313,19 @@ "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "出力ファイルの最初に UTF-8 バイト順マーク(BOM) を生成します。", "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "個々のファイルを持つ代わりに、複数のソース マップを含む単一ファイルを生成します。", "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "単一ファイル内で sourcemap と共にソースを生成します。'--inlineSourceMap' または '--sourceMap' を設定する必要があります。", - "Enable_all_strict_type_checking_options_6180": "strict 型チェックのオプションをすべて有効にします。", + "Enable_all_strict_type_checking_options_6180": "厳密な型チェックのオプションをすべて有効にします。", "Enable_strict_checking_of_function_types_6186": "関数の型の厳密なチェックを有効にします。", "Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。", "Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。", "Enable_tracing_of_the_name_resolution_process_6085": "名前解決の処理のトレースを有効にします。", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "すべてのインポートの名前空間オブジェクトを作成して、CommonJS と ES モジュール間の生成の相互運用性を有効にします。'allowSyntheticDefaultImports' を暗黙のうちに表します。", "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 非同期関数用の実験的なサポートを有効にします。", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 デコレーター用の実験的なサポートを有効にします。", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "デコレーター用の型メタデータを発行するための実験的なサポートを有効にします。", "Enum_0_used_before_its_declaration_2450": "列挙型 '{0}' は宣言の前に使用されました。", - "Enum_declarations_must_all_be_const_or_non_const_2473": "enum 宣言は、すべてが定数、またはすべてが非定数でなければなりません。", + "Enum_declarations_must_all_be_const_or_non_const_2473": "列挙型宣言は、すべてが定数、またはすべてが非定数でなければなりません。", "Enum_member_expected_1132": "列挙型メンバーが必要です。", - "Enum_member_must_have_initializer_1061": "列挙メンバーには初期化子が必要です。", + "Enum_member_must_have_initializer_1061": "列挙型メンバーには初期化子が必要です。", "Enum_name_cannot_be_0_2431": "列挙型の名前を '{0}' にすることはできません。", "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "列挙型 '{0}' に、リテラルではない初期化子を持つメンバーがあります。", "Examples_Colon_0_6026": "例: {0}", @@ -340,9 +350,9 @@ "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "エクスポートされた外部パッケージの型指定のファイル '{0}' はモジュールではありません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "エクスポートされた外部パッケージの型指定のファイルにトリプルスラッシュ参照を含めることはできません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "エクスポートされた型のエイリアス '{0}' にプライベート名 '{1}' が付いているか、その名前を使用しています。", - "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を使用しています。", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を持っているか、使用しています。", "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。", "Expression_expected_1109": "式が必要です。", "Expression_or_comma_expected_1137": "式またはコンマが必要です。", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "ファイル名 '{0}' は、既に含まれているファイル名 '{1}' と大文字と小文字の指定だけが異なります。", "File_name_0_has_a_1_extension_stripping_it_6132": "ファイル名 '{0}' に '{1}' 拡張子が使われています - 削除しています。", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "ファイルの指定で再帰ディレクトリのワイルドカード ('**') の後に親ディレクトリ ('..') を指定することはできません: '{0}'。", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "ファイルの指定に複数の再帰的なディレクトリのワイルドカード ('**') を含めることはできません: '{0}'。", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "ファイルの指定の末尾を再帰的なディレクトリのワイルドカード ('**') にすることはできません: '{0}'。", "Found_package_json_at_0_6099": "'{0}' で 'package.json' が見つかりました。", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "'ES3' または 'ES5' を対象としている場合、関数宣言は厳格モードのブロック内では許可されていません。", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "識別子が必要です。'{0}' は、厳格モードの予約語です。モジュールは自動的に厳格モードになります。", "Identifier_expected_1003": "識別子が必要です。", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "識別子が必要です。'__esModule' は、ECMAScript モジュールを変換するときのエクスポート済みマーカーとして予約されています。", - "Ignore_this_error_message_90019": "このエラー メッセージを無視します。", - "Implement_inherited_abstract_class_90007": "継承抽象クラスを実装します。", - "Implement_interface_0_90006": "インターフェイス '{0}' を実装します。", - "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を使用しています。", - "Import_0_from_module_1_90013": "モジュール \"{1}\" から '{0}' をインポートします。", + "Ignore_this_error_message_90019": "このエラー メッセージを無視する", + "Implement_inherited_abstract_class_90007": "継承抽象クラスを実装する", + "Implement_interface_0_90006": "インターフェイス '{0}' を実装する", + "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を持っているか、使用しています。", + "Import_0_from_module_1_90013": "モジュール \"{1}\" から '{0}' をインポートする", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート割り当てを使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。", "Import_declaration_0_is_using_private_name_1_4000": "インポート宣言 '{0}' がプライベート名 '{1}' を使用しています。", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "インポート宣言が、'{0}' のローカル宣言と競合しています。", @@ -418,16 +427,16 @@ "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "アンビエント モジュール宣言内のインポート宣言またはエクスポート宣言は、相対モジュール名を通してモジュールを参照することはできません。", "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "インポートはモジュールの拡張では許可されていません。外側の外部モジュールに移動することを検討してください。", "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "アンビエント列挙型の宣言では、メンバー初期化子は定数式である必要があります。", - "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "複数の宣言がある列挙型で、最初の列挙要素の初期化子を省略できる宣言は 1 つのみです。", "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' 列挙型の宣言で、メンバー初期化子は定数式でなければなりません。", "Index_signature_in_type_0_only_permits_reading_2542": "型 '{0}' のインデックス シグネチャは、読み取りのみを許可します。", "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}' を初期化します。", + "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}' を参照できません。", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "パラメーター '{0}' の初期化子はその後で宣言された識別子 '{1}' を参照できません。", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初期化子にこのバインド要素の値が提示されていません。またバインド要素に既定値がありません。", @@ -484,14 +493,15 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "ロケールは または - の形式で指定する必要があります (例: '{0}'、'{1}')。", "Longest_matching_prefix_for_0_is_1_6108": "'{0}' の一致する最長プレフィックスは '{1}' です。", "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' フォルダーを検索しています。最初の場所は '{0}' です。", - "Make_super_call_the_first_statement_in_the_constructor_90002": "'super()' 呼び出しをコンストラクター内の最初のステートメントにします。", + "Make_super_call_the_first_statement_in_the_constructor_90002": "'super()' 呼び出しをコンストラクター内の最初のステートメントにする", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "マップされたオブジェクト型のテンプレートの型は暗黙的に 'any' になります。", "Member_0_implicitly_has_an_1_type_7008": "メンバー '{0}' の型は暗黙的に '{1}' になります。", "Merge_conflict_marker_encountered_1185": "マージ競合マーカーが検出されました。", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "マージされた宣言 '{0}' に既定のエクスポート宣言を含めることはできません。代わりに、'export default {0}' 宣言を別個に追加することを検討してください。", "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013": "メタプロパティ '{0}' は、関数の宣言の本文、関数の式、またはコンストラクターでのみ許可されています。", "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "メソッド '{0}' は abstract に指定されているため、実装を含めることができません。", - "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "エクスポートされたインターフェイスのメソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "エクスポートされたインターフェイスのメソッド '{0}' がプライベート名 '{1}' を使用しています。", + "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "エクスポートされたインターフェイスのメソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "エクスポートされたインターフェイスのメソッド '{0}' がプライベート名 '{1}' を持っているか、使用しています。", "Modifiers_cannot_appear_here_1184": "ここで修飾子を使用することはできません。", "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "モジュール {0} は既に '{1}' という名前のメンバーをエクスポートしています。あいまいさを解決するため、明示的にもう一度エクスポートすることを検討してください。", "Module_0_has_no_default_export_1192": "モジュール '{0}' に既定エクスポートがありません。", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== モジュール名 '{0}' が正常に '{1}' に解決されました。========", "Module_resolution_kind_is_not_specified_using_0_6088": "モジュール解決の種類が '{0}' を使用して指定されていません。", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' を使用したモジュール解決が失敗しました。", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "複数の連続した数値区切り記号を指定することはできません。", "Multiple_constructor_implementations_are_not_allowed_2392": "コンストラクターを複数実装することはできません。", "NEWLINE_6061": "改行", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "'{1}' 型および '{2}' 型の名前付きプロパティ '{0}' が一致しません。", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象クラスの式はクラス '{1}' からの継承抽象メンバー '{0}' を実装しません。", "Not_all_code_paths_return_a_value_7030": "一部のコード パスは値を返しません。", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "数値インデックス型 '{0}' を文字列インデックス型 '{1}' に割り当てることはできません。", + "Numeric_separators_are_not_allowed_here_6188": "数値の区切り記号は、ここでは使用できません。", "Object_is_possibly_null_2531": "オブジェクトは 'null' である可能性があります。", "Object_is_possibly_null_or_undefined_2533": "オブジェクトは 'null' か 'undefined' である可能性があります。", "Object_is_possibly_undefined_2532": "オブジェクトは 'undefined' である可能性があります。", @@ -526,7 +538,7 @@ "Object_literal_s_property_0_implicitly_has_an_1_type_7018": "オブジェクト リテラルのプロパティ '{0}' の型は暗黙的に '{1}' になります。", "Octal_digit_expected_1178": "8 進の数字が必要です。", "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017": "8 進数のリテラル型には、ES2015 構文を使用する必要があります。構文 '{0}' を使用してください。", - "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8 進数のリテラルは、列挙メンバーの初期化子では許可されていません。構文 '{0}' を使用してください。", + "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8 進数のリテラルは、列挙型メンバーの初期化子では許可されていません。構文 '{0}' を使用してください。", "Octal_literals_are_not_allowed_in_strict_mode_1121": "厳格モードでは Octal リテラルは使用できません。", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 以降を対象にする場合、8 進数のリテラルは使用できません。構文 '{0}' を使用してください。", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' ステートメントで使用できる変数宣言は 1 つのみです。", @@ -556,46 +568,47 @@ "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "パラメーター '{0}' はその初期化子内では参照できません。", "Parameter_0_implicitly_has_an_1_type_7006": "パラメーター '{0}' の型は暗黙的に '{1}' になります。", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "パラメーター '{0}' がパラメーター '{1}' と同じ位置にありません。", - "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート名 '{1}' を使用しています。", - "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' がプライベート名 '{1}' を使用しています。", - "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート名 '{1}' を使用しています。", - "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "エクスポートされた関数のパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "エクスポートされた関数のパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "エクスポートされた関数のパラメーター '{0}' がプライベート名 '{1}' を使用しています。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "エクスポートされたインターフェイスの呼び出しシグネチャのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "エクスポートされたクラスのコンストラクターのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "エクスポートされたインターフェイスのコンストラクター シグネチャのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "エクスポートされた関数のパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "エクスポートされた関数のパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "エクスポートされた関数のパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート モジュール '{2}' の名前 '{1}' が指定されているか使用されています。", "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "エクスポートされたインターフェイスのインデックス シグネチャのパラメーター '{0}' で、プライベート名 '{1}' が指定されているか使用されています。", - "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' がプライベート名 '{1}' を使用しています。", - "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' がプライベート名 '{1}' を使用しています。", - "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "エクスポートされたインターフェイスのメソッドのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "エクスポートされたクラスのパブリック メソッドのパラメーター '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "エクスポートされたクラスのパブリック静的メソッドのパラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", "Parameter_cannot_have_question_mark_and_initializer_1015": "パラメーターに疑問符および初期化子を指定することはできません。", "Parameter_declaration_expected_1138": "パラメーター宣言が必要です。", - "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート名 '{1}' を使用しています。", - "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート名 '{1}' を使用しています。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "エクスポートされたクラスのパブリック セッター '{0}' のパラメーター型が、プライベート名 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "エクスポートされたクラスのパブリック静的セッター '{0}' のパラメーター型が、プライベート名 '{1}' を持っているか、使用しています。", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "厳格モードで解析してソース ファイルごとに \"use strict\" を生成します。", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "パターン '{0}' に使用できる '*' 文字は最大で 1 つです。", - "Prefix_0_with_an_underscore_90025": "アンダースコアを含むプレフィックス '{0}'。", + "Prefix_0_with_an_underscore_90025": "アンダースコアを含むプレフィックス '{0}'", "Print_names_of_files_part_of_the_compilation_6155": "コンパイルの一環としてファイルの名前を書き出します。", "Print_names_of_generated_files_part_of_the_compilation_6154": "コンパイルの一環として生成されたファイル名を書き出します。", "Print_the_compiler_s_version_6019": "コンパイラのバージョンを表示します。", "Print_this_message_6017": "このメッセージを表示します。", - "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙 '{1}' に存在しません。", + "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "プロパティ '{0}' は型 '{1}' に存在していません。'{2}' ですか?", "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "プロパティ '{0}' には競合する宣言があり、型 '{1}' ではアクセスできません。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "プロパティ '{0}' に初期化子がなく、コンストラクターで明確に割り当てられていません。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。get アクセサーには戻り値の型の注釈がないためです。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。set アクセサーにはパラメーター型の注釈がないためです。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "型 '{1}' のプロパティ '{0}' を基本データ型 '{2}' の同じプロパティに割り当てることはできません。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "型 '{1}' のプロパティ '{0}' を型 '{2}' に割り当てることはできません。", "Property_0_is_declared_but_its_value_is_never_read_6138": "プロパティ '{0}' が宣言されていますが、その値が読み取られることはありません。", "Property_0_is_incompatible_with_index_signature_2530": "プロパティ '{0}' はインデックス シグネチャと互換性がありません。", @@ -610,8 +623,8 @@ "Property_0_is_used_before_being_assigned_2565": "プロパティ '{0}' は割り当てられる前に使用されています。", "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606": "JSX のスプレッド属性のプロパティ '{0}' をターゲット プロパティに割り当てることはできません。", "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094": "エクスポートされたクラスの式のプロパティ '{0}' が private または protected でない可能性があります。", - "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を使用しています。", + "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "型 '{1}' のプロパティ '{0}' を数値インデックス型 '{2}' に割り当てることはできません。", "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "型 '{1}' のプロパティ '{0}' を文字列インデックス型 '{2}' に割り当てることはできません。", "Property_assignment_expected_1136": "プロパティの割り当てが必要です。", @@ -619,22 +632,23 @@ "Property_or_signature_expected_1131": "プロパティまたはシグネチャが必要です。", "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "プロパティ値には、文字列リテラル、数値リテラル、'true'、'false'、'null'、オブジェクト リテラルまたは配列リテラルのみ使用できます。", "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179": "'for-of' の iterable、spread、'ES5' や 'ES3' をターゲットとする場合は destructuring に対してフル サポートを提供します。", - "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "エクスポートされたクラスのパブリック メソッド '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "エクスポートされたクラスのパブリック メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "エクスポートされたクラスのパブリック メソッド '{0}' がプライベート名 '{1}' を使用しています。", - "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "エクスポートされたクラスのパブリック プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート名 '{1}' を使用しています。", - "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "エクスポートされたクラスのパブリック静的メソッド '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート名 '{1}' を使用しています。", - "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート名 '{1}' を使用しています。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "エクスポートされたクラスのパブリック メソッド '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "エクスポートされたクラスのパブリック メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "エクスポートされたクラスのパブリック メソッド '{0}' がプライベート名 '{1}' を持っているか、使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "エクスポートされたクラスのパブリック プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "エクスポートされたクラスのパブリック プロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "エクスポートされたクラスのパブリック静的メソッド '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "エクスポートされたクラスのパブリック静的メソッド '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "エクスポートされたクラスのパブリック静的プロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "暗黙的な 'any' 型を含む式と宣言に関するエラーを発生させます。", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", - "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除します: {0}。", + "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'", + "Replace_import_with_0_95015": "インポートを '{0}' に置換します。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "関数の一部のコード パスが値を返さない場合にエラーを報告します。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch ステートメントに case のフォールスルーがある場合にエラーを報告します。", "Report_errors_in_js_files_8019": ".js ファイルのエラーを報告します。", @@ -654,33 +668,33 @@ "Resolving_with_primary_search_path_0_6121": "プライマリ検索パス '{0}' で解決しています。", "Rest_parameter_0_implicitly_has_an_any_type_7019": "Rest パラメーター '{0}' の型は暗黙的に 'any[]' になります。", "Rest_types_may_only_be_created_from_object_types_2700": "rest 型はオブジェクトの種類からのみ作成できます。", - "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", - "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート名 '{0}' を使用しています。", - "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", - "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047": "エクスポートされたインターフェイスの呼び出しシグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045": "エクスポートされたインターフェイスのコンストラクター シグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409": "コンストラクター シグネチャの戻り値の型は、クラスのインスタンス型に割り当て可能でなければなりません。", - "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "エクスポートされた関数の戻り値の型が外部モジュール {1} の名前 '{0}' を使用していますが、名前を指定することはできません。", - "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "エクスポートされた関数の戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", - "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "エクスポートされた関数の戻り値の型が、プライベート名 '{0}' を使用しています。", - "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", - "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート名 '{0}' を使用しています。", - "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", - "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート名 '{0}' を使用しています。", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を使用しています。", - "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "エクスポートされたクラスのパブリック メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を使用していますが、名前を指定することはできません。", - "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", - "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート名 '{0}' を使用しています。", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を使用していますが、名前を指定することはできません。", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を使用しています。", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を使用しています。", - "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を使用していますが、名前を指定することはできません。", - "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を使用しています。", - "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート名 '{0}' を使用しています。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058": "エクスポートされた関数の戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059": "エクスポートされた関数の戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_exported_function_has_or_is_using_private_name_0_4060": "エクスポートされた関数の戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "エクスポートされたインターフェイスのインデックス シグネチャの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "エクスポートされたインターフェイスのメソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "エクスポートされたクラスのパブリック ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を持っているか、使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "エクスポートされたクラスのパブリック メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "エクスポートされたクラスのパブリック メソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "エクスポートされたクラスのパブリック静的ゲッター '{0}' の戻り値の型が、プライベート名 '{1}' を持っているか、使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が外部モジュール {1} の名前 '{0}' を持っているか使用していますが、名前を指定することはできません。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート モジュール '{1}' の名前 '{0}' を持っているか、使用しています。", + "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "エクスポートされたクラスのパブリック静的メソッドの戻り値の型が、プライベート名 '{0}' を持っているか、使用しています。", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "'{0}' で生成されたモジュール解決は、前のプログラムから変更されていないため、再利用しています。", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "前のプログラムを再利用して、モジュール '{0}' をファイル '{1}' に解決しています。", - "Rewrite_as_the_indexed_access_type_0_90026": "インデックス化されたアクセスの種類 '{0}' として書き換えます。", + "Rewrite_as_the_indexed_access_type_0_90026": "インデックス付きのアクセスの種類 '{0}' として書き換える", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "ルート ディレクトリを決定できません。プライマリ検索パスをスキップします。", "STRATEGY_6039": "戦略", "Scoped_package_detected_looking_in_0_6182": "'{0}' 内を検索して、スコープ パッケージが検出されました", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "ソース マップ オプション", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "特殊化されたオーバーロード シグネチャは、特殊化されていないシグネチャに割り当てることはできません。", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "動的インポートの指定子にはスプレッド要素を指定できません。", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript のターゲット バージョンを指定します: 'ES3' (既定)、'ES5'、'ES2015'、'ES2016'、'ES2017'、'ESNEXT'。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript のターゲット バージョンを指定します: 'ES3' (既定)、'ES5'、'ES2015'、'ES2016'、'ES2017'、'ES2018'、'ESNEXT'。", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX コード生成を指定します: 'preserve'、'react-native'、'react'。", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "コンパイルに含めるライブラリ ファイルを指定します: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "モジュール コード生成を指定します: 'none'、'commonjs'、'amd'、'system'、'umd'、'es2015'、'ESNext'。", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "入力ファイルのルート ディレクトリを指定します。--outDir とともに、出力ディレクトリ構造の制御に使用します。", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 式のスプレッド演算子は ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", "Spread_types_may_only_be_created_from_object_types_2698": "spread 型はオブジェクトの種類からのみ作成できます。", + "Starting_compilation_in_watch_mode_6031": "ウォッチ モードでのコンパイルを開始しています...", "Statement_expected_1129": "ステートメントが必要です。", "Statements_are_not_allowed_in_ambient_contexts_1036": "ステートメントは環境コンテキストでは使用できません。", "Static_members_cannot_reference_class_type_parameters_2302": "静的メンバーはクラスの型パラメーターを参照できません。", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "文字列リテラルが必要です。", "String_literal_with_double_quotes_expected_1327": "二重引用符を含む文字列リテラルが必要です。", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "色とコンテキストを使用してエラーとメッセージにスタイルを適用します (試験的)。", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "後続のプロパティ宣言は同じ型でなければなりません。プロパティ '{0}' の型は '{1}' である必要がありますが、ここでは型が '{2}' になっています。", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "後続の変数宣言は同じ型でなければなりません。変数 '{0}' の型は '{1}' である必要がありますが、'{2}' になっています。", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "パターン '{1}' の代入 '{0}' の型が正しくありません。必要な型は 'string' ですが、'{2}' を取得しました。", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "パターン '{1}' の代入 '{0}' に使用できる '*' 文字は最大 1 つです。", @@ -732,7 +747,7 @@ "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "'arguments' オブジェクトは、ES3 および ES5 の非同期関数またはメソッドで参照することはできません。標準の関数またはメソッドを使用することを検討してください。", "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' ステートメントの本文を空のステートメントにすることはできません。", "The_character_set_of_the_input_files_6163": "入力ファイルの文字セット。", - "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "制御フロー解析に含まれている関数またはモジュールの本体が大きすぎます。", + "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "含まれている関数またはモジュールの本体は、制御フロー解析には大きすぎます。", "The_current_host_does_not_support_the_0_option_5001": "現在のホストは '{0}' オプションをサポートしていません。", "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの割り当ての式は、環境コンテキストの識別子または修飾名にする必要があります。", "The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "型 '{0}' は、配列型でも文字列型でもないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "型 '{0}' は、配列型ではないか、反復子を返す '[Symbol.iterator]()' メソッドを持っていません。", "Type_0_is_not_assignable_to_type_1_2322": "型 '{0}' を型 '{1}' に割り当てることはできません。", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "型 '{0}' は型 '{1}' に割り当てられません。同じ名前で 2 つの異なる型が存在しますが、これは関連していません。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "型 '{0}' は型 '{1}' に割り当てられません。同じ名前で 2 つの異なる型が存在しますが、これは関連していません。", "Type_0_is_not_comparable_to_type_1_2678": "型 '{0}' は型 '{1}' と比較できません。", "Type_0_is_not_generic_2315": "型 '{0}' はジェネリックではありません。", "Type_0_provides_no_match_for_the_signature_1_2658": "型 '{0}' にはシグネチャ '{1}' に一致するものがありません。", @@ -818,15 +833,15 @@ "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}' を使用しています。", - "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "エクスポートされた関数の型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", - "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "エクスポートされたインターフェイスの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "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}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016": "エクスポートされた関数の型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004": "エクスポートされたインターフェイスの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083": "エクスポートした型のエイリアスの型パラメーター '{0}' にプライベート名 '{1}' が指定されているか、これを使用しています。", - "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "エクスポートされたインターフェイスのメソッドの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", - "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "エクスポートされたクラスのパブリック メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", - "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "エクスポートされたクラスのパブリック静的メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を使用しています。", + "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014": "エクスポートされたインターフェイスのメソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012": "エクスポートされたクラスのパブリック メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", + "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010": "エクスポートされたクラスのパブリック静的メソッドの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", "Type_parameter_declaration_expected_1139": "型パラメーターの宣言が必要です。", "Type_parameter_list_cannot_be_empty_1098": "型パラメーター リストを空にすることはできません。", "Type_parameter_name_cannot_be_0_2368": "型パラメーター名を '{0}' にすることはできません。", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "未終了のテンプレート リテラルです。", "Untyped_function_calls_may_not_accept_type_arguments_2347": "型指定のない関数の呼び出しで型引数を使用することはできません。", "Unused_label_7028": "未使用のラベル。", + "Use_synthetic_default_member_95016": "合成 'default' メンバーを使用します。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", "VERSION_6036": "バージョン", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "型 '{0}' の値には、型 '{1}' と共通のプロパティがありません。呼び出しますか?", @@ -911,17 +927,17 @@ "class_expressions_are_not_currently_supported_9003": "'class' 式は現在サポートされていません。", "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' 宣言は、ブロック内でのみ宣言できます。", "const_declarations_must_be_initialized_1155": "'const' 宣言は初期化する必要があります。", - "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列挙メンバーの初期化子が、無限値に評価されました。", - "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列挙メンバーの初期化子が、許可されない値 'NaN' に評価されました。", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、あるいはインポート宣言またはエクスポート割り当ての右辺にのみ使用できます。", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列挙型メンバーの初期化子が、無限値に評価されました。", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列挙型メンバーの初期化子が、許可されない値 'NaN' に評価されました。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの割り当ての右辺、型のクエリにのみ使用できます。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。", - "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum 宣言' を使用できるのは .ts ファイル内のみです。", + "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'列挙型宣言' を使用できるのは .ts ファイル内のみです。", "export_can_only_be_used_in_a_ts_file_8003": "'export=' を使用できるのは .ts ファイル内のみです。", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "環境モジュールとモジュール拡張は常に表示されるので、これらに 'export' 修飾子を適用することはできません。", "extends_clause_already_seen_1172": "'extends' 句は既に存在します。", "extends_clause_must_precede_implements_clause_1173": "extends' 句は 'implements' 句の前に指定しなければなりません。", - "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "エクスポートされたクラス '{0}' の 'extends' 句がプライベート名 '{1}' を使用しています。", - "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "エクスポートされたインターフェイス '{0}' の 'extends' 句がプライベート名 '{1}' を使用しています。", + "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "エクスポートされたクラス '{0}' の 'extends' 句がプライベート名 '{1}' を持っているか、使用しています。", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "エクスポートされたインターフェイス '{0}' の 'extends' 句がプライベート名 '{1}' を持っているか、使用しています。", "file_6025": "ファイル", "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' アクセサーおよび 'set' アクセサーには、同じ 'this' 型が必要です。", "get_and_set_accessor_must_have_the_same_type_2380": "'get' アクセサーと 'set' アクセサーは同じ型でなければなりません。", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'型アサーション式' を使用できるのは、.ts ファイル内のみです。", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'型パラメーター宣言' を使用できるのは .ts ファイル内のみです。", "types_can_only_be_used_in_a_ts_file_8010": "'型' を使用できるのは .ts ファイル内のみです。", - "unique_symbol_types_are_not_allowed_here_1335": "'一意のシンボル' 型はここでは許可されていません。", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'一意のシンボル' 型は変数ステートメントの変数でのみ許可されています。", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'一意のシンボル' 型は、バインディング名を持つ変数の宣言では使用できません。", + "unique_symbol_types_are_not_allowed_here_1335": "'unique symbol' 型はここでは許可されていません。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' 型は変数ステートメントの変数でのみ許可されています。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 型は、バインディング名を持つ変数の宣言では使用できません。", "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 式は、非同期関数ブロックでは使用できません。", "with_statements_are_not_allowed_in_strict_mode_1101": "厳格モードでは 'with' ステートメントは使用できません。", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 式は、パラメーター初期化子では使用できません。" diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index 1da5977910679..c73788cab9f62 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -12,11 +12,11 @@ "A_class_member_cannot_have_the_0_keyword_1248": "클래스 멤버에는 '{0}' 키워드를 사용할 수 없습니다.", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "쉼표 식은 컴퓨팅된 속성 이름에 사용할 수 없습니다.", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "계산된 속성 이름에서는 포함하는 형식의 형식 매개 변수를 참조할 수 없습니다.", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "클래스 속성 선언의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "메서드 오버로드의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "리터럴 형식의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "앰비언트 컨텍스트의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "인터페이스의 계산된 속성 이름은 형식이 리터럴 형식이거나 '고유 기호' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "클래스 속성 선언의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "메서드 오버로드의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "리터럴 형식의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "앰비언트 컨텍스트의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "인터페이스의 계산된 속성 이름은 형식이 리터럴 형식이거나 'unique symbol' 형식인 식을 참조해야 합니다.", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "계산된 속성 이름은 'string', 'number', 'symbol' 또는 'any' 형식이어야 합니다.", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "'{0}' 양식의 계산된 속성 이름은 'symbol' 형식이어야 합니다.", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "const 열거형 멤버는 문자열 리터럴을 통해서만 액세스할 수 있습니다.", @@ -33,7 +33,7 @@ "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "이 컨텍스트에서는 한정된 할당 어설션 '!'가 허용되지 않습니다.", "A_destructuring_declaration_must_have_an_initializer_1182": "구조 파괴 선언에 이니셜라이저가 있어야 합니다.", "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "ES5/ES3의 동적 가져오기 호출에 'Promise' 생성자가 필요합니다. 'Promise' 생성자에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", - "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "동적 가져오기 호출은 'Promise'를 반환해야 합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", + "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "동적 가져오기 호출은 'Promise'를 반환합니다. 'Promise'에 대한 선언이 있거나 `--lib` 옵션에 'ES2015'가 포함되었는지 확인하세요.", "A_file_cannot_have_a_reference_to_itself_1006": "파일은 자신에 대한 참조를 포함할 수 없습니다.", "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103": "'for-await-of' 식은 비동기 함수 또는 비동기 생성기 내에서만 사용할 수 있습니다.", "A_function_returning_never_cannot_have_a_reachable_end_point_2534": "'never'를 반환하는 함수에는 연결 가능한 끝점이 있을 수 없습니다.", @@ -48,14 +48,15 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수와 다른 파일에 있을 수 없습니다,", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수 앞에 있을 수 없습니다.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "네임스페이스 선언은 네임스페이스 또는 모듈에서만 사용할 수 있습니다.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "네임스페이스 스타일 가져오기를 호출하거나 생성할 수 없으며 런타임 시 오류가 발생합니다.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "매개 변수 이니셜라이저는 함수 또는 생성자 구현에서만 허용됩니다.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "rest 매개 변수를 사용하여 매개 변수 속성을 선언할 수 없습니다.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "매개 변수 속성은 생성자 구현에서만 허용됩니다.", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "바인딩 패턴을 사용하여 매개 변수 속성을 선언할 수 없습니다.", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "'extends' 옵션의 경로는 상대 경로이거나 루트 경로여야 하지만 '{0}'은(는) 아닙니다.", "A_promise_must_have_a_then_method_1059": "프라미스에는 'then' 메서드가 있어야 합니다.", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "형식이 '고유 기호' 형식인 클래스의 속성은 'static'과 'readonly' 둘 다여야 합니다.", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "형식이 '고유 기호' 형식인 인터페이스 또는 형식 리터럴의 속성은 'readonly'여야 합니다.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "형식이 'unique symbol' 형식인 클래스의 속성은 'static'과 'readonly' 둘 다여야 합니다.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "형식이 'unique symbol' 형식인 인터페이스 또는 형식 리터럴의 속성은 'readonly'여야 합니다.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "필수 매개 변수는 선택적 매개 변수 뒤에 올 수 없습니다.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 요소에는 바인딩 패턴이 포함될 수 없습니다.", "A_rest_element_cannot_have_an_initializer_1186": "rest 요소에는 이니셜라이저를 사용할 수 없습니다.", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "형식 조건자는 바인딩 패턴에서 '{0}' 요소를 참조할 수 없습니다.", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "형식 조건자는 함수 및 메서드의 반환 형식 위치에서만 사용할 수 있습니다.", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "형식 조건자의 형식을 해당 매개 변수의 형식에 할당할 수 있어야 합니다.", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "형식이 '고유한 기호' 형식인 변수는 'const'여야 합니다.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "형식이 'unique symbol' 형식인 변수는 'const'여야 합니다.", "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": "추상 메서드는 추상 클래스 내에서만 사용할 수 있습니다.", @@ -91,11 +92,12 @@ "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": "접근자는 모두 추상이거나 비추상이어야 합니다.", - "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\"에서 기존 가져오기 선언에 '{0}'을(를) 추가합니다.", - "Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처를 추가합니다.", - "Add_missing_super_call_90001": "누락된 'super()' 호출을 추가하세요.", - "Add_this_to_unresolved_variable_90008": "확인되지 않은 변수에 'this.'을 추가하세요.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "tsconfig.json 파일을 추가하면 TypeScript 파일과 JavaScript 파일이 둘 다 포함된 프로젝트를 정리하는 데 도움이 됩니다. 자세한 내용은 https://aka.ms/tsconfig를 참조하세요.", + "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\"에서 기존 가져오기 선언에 '{0}' 추가", + "Add_async_modifier_to_containing_function_90029": "포함된 함수에 async 한정자 추가", + "Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처 추가", + "Add_missing_super_call_90001": "누락된 'super()' 호출 추가", + "Add_this_to_unresolved_variable_90008": "확인되지 않은 변수에 'this.' 추가", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "tsconfig.json 파일을 추가하면 TypeScript 파일과 JavaScript 파일이 둘 다 포함된 프로젝트를 정리하는 데 도움이 됩니다. 자세한 내용은 https://aka.ms/tsconfig를 참조하세요.", "Additional_Checks_6176": "추가 검사", "Advanced_Options_6178": "고급 옵션", "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}'의 모든 선언에는 동일한 한정자가 있어야 합니다.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "인덱스 시그니처 매개 변수에는 액세스 가능성 한정자를 사용할 수 없습니다.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "인덱스 시그니처 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "인덱스 시그니처 매개 변수에는 형식 주석을 사용할 수 없습니다.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "인덱스 시그니처 매개 변수 형식은 형식 별칭일 수 없습니다. 대신 '[{0}: {1}]: {2}'을(를) 작성하세요.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "인덱스 시그니처 매개 변수 형식은 공용 구조체 형식일 수 없습니다. 대신 매핑된 개체 형식을 사용하세요.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "인덱스 시그니처 매개 변수 형식은 'string' 또는 'number'여야 합니다.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "인터페이스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 확장할 수 있습니다.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "인터페이스는 클래스 또는 다른 인터페이스만 확장할 수 있습니다.", @@ -165,7 +169,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_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}' 속성의 형식을 검색하려고 했나요?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "형식 선언 파일을 가져올 수 없습니다. '{1}' 대신 '{0}'을(를) 가져오세요.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "블록 범위 선언 '{1}'과(와) 동일한 범위 내에서 외부 범위 변수 '{0}'을(를) 초기화할 수 없습니다.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "형식에 호출 시그니처가 없는 식을 호출할 수 없습니다. '{0}' 형식에 호환되는 호출 시그니처가 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "'extends'를 'implements'로 변경하세요.", - "Change_spelling_to_0_90022": "철자를 '{0}'(으)로 변경하세요.", + "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}'에 대해 일치하는 가장 긴 접두사인지 확인하는 중입니다.", "Circular_definition_of_import_alias_0_2303": "가져오기 별칭 '{0}'의 순환 정의입니다.", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "구성을 확인하는 동안 순환이 검색되었습니다. {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "'{0}' 클래스가 인스턴스 멤버 함수 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 함수를 인스턴스 멤버 속성으로 정의합니다.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "'{0}' 클래스가 인스턴스 멤버 속성 '{1}'을(를) 정의하지만 확장 클래스 '{2}'은(는) 이 속성을 인스턴스 멤버 함수로 정의합니다.", "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' 클래스가 기본 클래스 '{1}'을(를) 잘못 확장합니다.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "'{0}' 클래스가 '{1}' 클래스를 잘못 구현합니다. '{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` 태그를 둘 이상 가질 수 없습니다.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.", "Convert_function_0_to_class_95002": "'{0}' 함수를 클래스로 변환", "Convert_function_to_an_ES2015_class_95001": "함수를 ES2015 클래스로 변환", + "Convert_to_ES6_module_95017": "ES6 모듈로 변환", "Convert_to_default_import_95013": "기본 가져오기로 변환", "Corrupted_locale_file_0_6051": "로캘 파일 {0}이(가) 손상되었습니다.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "모듈 '{0}'에 대한 선언 파일을 찾을 수 없습니다. '{1}'에는 암시적으로 'any' 형식이 포함됩니다.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "선언이 필요합니다.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "선언 이름이 기본 제공 전역 ID '{0}'과(와) 충돌합니다.", "Declaration_or_statement_expected_1128": "선언 또는 문이 필요합니다.", - "Declare_method_0_90023": "'{0}' 메서드를 선언합니다.", - "Declare_property_0_90016": "'{0}' 속성을 선언합니다.", - "Declare_static_method_0_90024": "'{0}' 정적 메서드를 선언합니다.", - "Declare_static_property_0_90027": "정적 속성 '{0}'을(를) 선언합니다.", + "Declare_method_0_90023": "'{0}' 메서드 선언", + "Declare_property_0_90016": "'{0}' 속성 선언", + "Declare_static_method_0_90024": "'{0}' 정적 메서드 선언", + "Declare_static_property_0_90027": "'{0}' 정적 속성 선언", "Decorators_are_not_valid_here_1206": "데코레이터는 여기에 사용할 수 없습니다.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "동일한 이름의 여러 get/set 접근자에 데코레이터를 적용할 수 없습니다.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "모듈의 기본 내보내기에서 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[사용되지 않음] 대신 '--skipLibCheck'를 사용합니다. 기본 라이브러리 선언 파일의 형식 검사를 건너뜁니다.", "Digit_expected_1124": "숫자가 필요합니다.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "'{0}' 디렉터리가 없으므로 이 디렉터리에서 모든 조회를 건너뜁니다.", - "Disable_checking_for_this_file_90018": "이 파일 확인을 사용하지 않도록 설정합니다.", + "Disable_checking_for_this_file_90018": "이 파일 확인을 사용하지 않도록 설정", "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript 프로젝트에 대한 크기 제한을 사용하지 않도록 설정합니다.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "함수 형식의 제네릭 시그니처에 대한 엄격한 검사를 사용하지 않도록 설정합니다.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "동일한 파일에 대해 대/소문자를 일관되지 않게 사용한 참조를 허용하지 않습니다.", @@ -298,7 +307,7 @@ "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "ECMAScript 2015 모듈을 대상을 지정할 때에는 동적 가져오기를 사용할 수 없습니다.", "Dynamic_import_cannot_have_type_arguments_1326": "동적 가져오기에는 형식 인수를 사용할 수 없습니다.", "Dynamic_import_must_have_one_specifier_as_an_argument_1324": "동적 가져오기에는 지정자 하나를 인수로 사용해야 합니다.", - "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에는 '{0}' 형식이 있습니다.", + "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "동적 가져오기의 지정자는 'string' 형식이어야 하지만 여기에서 형식은 '{0}'입니다.", "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "인덱스 식이 'number' 형식이 아니므로 요소에 암시적으로 'any' 형식이 있습니다.", "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017": "'{0}' 형식에 인덱스 시그니처가 없으므로 요소에 암시적으로 'any' 형식이 있습니다.", "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164": "출력 파일의 시작에서 UTF-8 BOM(바이트 순서 표시)을 내보냅니다.", @@ -306,9 +315,10 @@ "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "단일 파일 내에서 소스 맵과 함께 소스를 내보냅니다. '--inlineSourceMap' 또는 '--sourceMap'을 설정해야 합니다.", "Enable_all_strict_type_checking_options_6180": "엄격한 형식 검사 옵션을 모두 사용하도록 설정합니다.", "Enable_strict_checking_of_function_types_6186": "함수 형식에 대한 엄격한 검사를 사용하도록 설정합니다.", - "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용합니다.", + "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용하도록 설정합니다.", "Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.", "Enable_tracing_of_the_name_resolution_process_6085": "이름 확인 프로세스 추적을 사용하도록 설정하세요.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "모든 가져오기에 대한 네임스페이스 개체를 만들어 CommonJS 및 ES 모듈 간의 내보내기 상호 운용성을 사용하도록 설정합니다. 'allowSyntheticDefaultImports'를 의미합니다.", "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 비동기 함수에 대해 실험적 지원을 사용합니다.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 데코레이터에 대해 실험적 지원을 사용합니다.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "데코레이터에 대한 형식 메타데이터를 내보내기 위해 실험적 지원을 사용합니다.", @@ -333,7 +343,7 @@ "Experimental_Options_6177": "실험적 옵션", "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "데코레이터에 대한 실험적 지원 기능은 이후 릴리스에서 변경될 수 있습니다. 이 경고를 제거하려면 'experimentalDecorators' 옵션을 설정하세요.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "명시적으로 지정된 모듈 확인 종류 '{0}'입니다.", - "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript 모듈을 대상으로 하는 경우 할당 내보내기를 사용할 수 없습니다. 대신 'export default'나 다른 모듈 형식 사용을 고려하세요.", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript 모듈을 대상으로 하는 경우 내보내기 할당을 사용할 수 없습니다. 대신 'export default'나 다른 모듈 형식의 사용을 고려하세요.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "'--module' 플래그가 'system'이면 내보내기 할당은 지원되지 않습니다.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "내보내기 선언이 '{0}'의 내보낸 선언과 충돌합니다.", "Export_declarations_are_not_permitted_in_a_namespace_1194": "네임스페이스에서는 내보내기 선언이 허용되지 않습니다.", @@ -343,7 +353,7 @@ "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "내보낸 변수 '{0}'이(가) 외부 모듈 {2}의 '{1}' 이름을 가지고 있거나 사용 중이지만 명명할 수 없습니다.", "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "내보낸 변수 '{0}'이(가) 전용 모듈 '{2}'의 '{1}' 이름을 가지고 있거나 사용 중입니다.", "Exported_variable_0_has_or_is_using_private_name_1_4025": "내보낸 변수 '{0}'이(가) 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "내보내기 및 할당 내보내기는 모듈 확대에서 허용되지 않습니다.", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "내보내기 및 내보내기 할당는 모듈 확대에서 허용되지 않습니다.", "Expression_expected_1109": "식이 필요합니다.", "Expression_or_comma_expected_1137": "식 또는 쉼표가 필요합니다.", "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "컴파일러가 기본 클래스 참조를 캡처하기 위해 사용하는 '_super'로 식이 확인됩니다.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "'{0}' 파일 이름은 이미 포함된 '{1}' 파일 이름과 대/소문자만 다릅니다.", "File_name_0_has_a_1_extension_stripping_it_6132": "파일 이름 '{0}'에 '{1}' 확장명이 있어 제거하는 중입니다.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "파일 사양은 재귀 디렉터리 와일드카드('**') 뒤에 나타나는 부모 디렉터리('..')를 포함할 수 없습니다. '{0}'.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "파일 사양은 여러 개의 재귀 디렉터리 와일드카드('**')를 포함할 수 없습니다. '{0}'.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "파일 사양은 재귀 디렉터리 와일드카드('**')로 끝날 수 없습니다. '{0}'.", "Found_package_json_at_0_6099": "'{0}'에서 'package.json'을 찾았습니다.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "'ES3' 또는 'ES5'를 대상으로 할 경우 strict 모드의 블록 내에서 함수 선언을 사용할 수 없습니다.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "식별자가 필요합니다. '{0}'은(는) strict 모드의 예약어입니다. 모듈은 자동으로 strict 모드가 됩니다.", "Identifier_expected_1003": "식별자가 필요합니다.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "식별자가 필요합니다. '__esModule'은 ECMAScript 모듈을 변환할 때 내보낸 표식으로 예약되어 있습니다.", - "Ignore_this_error_message_90019": "이 오류 메시지를 무시합니다.", - "Implement_inherited_abstract_class_90007": "상속된 추상 클래스를 구현하세요.", - "Implement_interface_0_90006": "'{0}' 인터페이스를 구현하세요.", + "Ignore_this_error_message_90019": "이 오류 메시지 무시", + "Implement_inherited_abstract_class_90007": "상속된 추상 클래스 구현", + "Implement_interface_0_90006": "'{0}' 인터페이스 구현", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "내보낸 클래스 '{0}'의 Implements 절이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", - "Import_0_from_module_1_90013": "\"{1}\" 모듈에서 '{0}'을(를) 가져옵니다.", + "Import_0_from_module_1_90013": "\"{1}\" 모듈에서 '{0}' 가져오기", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript 모듈을 대상으로 하는 경우 할당 가져오기를 사용할 수 없습니다. 대신 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' 또는 다른 모듈 형식 사용을 고려하세요.", "Import_declaration_0_is_using_private_name_1_4000": "가져오기 선언 '{0}'이(가) 전용 이름 '{1}'을(를) 사용하고 있습니다.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "가져오기 선언이 '{0}'의 로컬 선언과 충돌합니다.", @@ -424,10 +433,10 @@ "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}'을(를) 초기화합니다.", + "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}'을(를) 참조할 수 없습니다.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "매개 변수 '{0}'의 이니셜라이저는 그 다음에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "이니셜라이저는 이 바인딩 요소에 대한 값을 제공하지 않으며 바인딩 요소에는 기본값이 없습니다.", @@ -480,11 +489,12 @@ "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168": "런타임에 프로젝트의 구조를 나타내는 결합된 콘텐츠가 있는 루트 폴더의 목록입니다.", "Loading_0_from_the_root_dir_1_candidate_location_2_6109": "루트 디렉터리 '{1}'에서 '{0}'을(를) 로드하고 있습니다. 후보 위치: '{2}'.", "Loading_module_0_from_node_modules_folder_target_file_type_1_6098": "'node_modules' 폴더에서 '{0}' 모듈을 로드하고 있습니다. 대상 파일 형식은 '{1}'입니다.", - "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "모듈을 파일/폴더로 로드하고 있습니다. 후보 모듈 위치: '{0}', 대상 파일 형식: '{1}'.", + "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095": "모듈을 파일/폴더로 로드하고 있습니다. 후보 모듈 위치는 '{0}', 대상 파일 형식은 '{1}'입니다.", "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "로캘이 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.", "Longest_matching_prefix_for_0_is_1_6108": "'{0}'에 대해 일치하는 가장 긴 접두사는 '{1}'입니다.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' 폴더에서 찾고 있습니다. 초기 위치: '{0}'.", - "Make_super_call_the_first_statement_in_the_constructor_90002": "생성자의 첫 번째 문을 'super()'로 호출하세요.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "생성자의 첫 번째 문을 'super()'로 호출", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "매핑된 개체 형식에는 'any' 템플릿 형식이 암시적으로 포함됩니다.", "Member_0_implicitly_has_an_1_type_7008": "'{0}' 멤버에는 암시적으로 '{1}' 형식이 포함됩니다.", "Merge_conflict_marker_encountered_1185": "병합 충돌 표식을 발견했습니다.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "병합된 선언 '{0}'에는 기본 내보내기 선언을 포함할 수 없습니다. 대신 별도의 'export default {0}' 선언을 추가하세요.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 모듈 이름 '{0}'이(가) '{1}'(으)로 확인되었습니다. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "모듈 확인 종류가 지정되지 않았습니다. '{0}'을(를) 사용합니다.", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs'를 사용한 모듈 확인에 실패했습니다.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "여러 개의 연속된 숫자 구분 기호는 허용되지 않습니다.", "Multiple_constructor_implementations_are_not_allowed_2392": "여러 생성자 구현은 허용되지 않습니다.", "NEWLINE_6061": "줄 바꿈", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "명명된 속성 '{0}'의 형식 '{1}' 및 '{2}'이(가) 동일하지 않습니다.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "비추상 클래스 식은 '{1}' 클래스에서 상속된 추상 멤버 '{0}'을(를) 구현하지 않습니다.", "Not_all_code_paths_return_a_value_7030": "일부 코드 경로가 값을 반환하지 않습니다.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "숫자 인덱스 형식 '{0}'을(를) 문자열 인덱스 형식 '{1}'에 할당할 수 없습니다.", + "Numeric_separators_are_not_allowed_here_6188": "숫자 구분 기호는 여기에서 허용되지 않습니다.", "Object_is_possibly_null_2531": "개체가 'null'인 것 같습니다.", "Object_is_possibly_null_or_undefined_2533": "개체가 'null' 또는 'undefined'인 것 같습니다.", "Object_is_possibly_undefined_2532": "개체가 'undefined'인 것 같습니다.", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "내보낸 클래스에 있는 공용 정적 setter '{0}'의 매개 변수 형식이 전용 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "strict 모드에서 구문 분석하고 각 소스 파일에 대해 \"use strict\"를 내보냅니다.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' 패턴에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", - "Prefix_0_with_an_underscore_90025": "'{0}' 앞에 밑줄을 붙이세요.", + "Prefix_0_with_an_underscore_90025": "'{0}' 앞에 밑줄 추가", "Print_names_of_files_part_of_the_compilation_6155": "컴파일의 일부인 파일의 이름을 인쇄합니다.", "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "속성 '{0}'은(는) 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' 속성에는 해당 get 접근자에 반환 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' 속성에는 해당 set 접근자에 매개 변수 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' 형식의 '{0}' 속성을 기본 형식 '{2}'의 동일한 속성에 할당할 수 없습니다.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' 형식의 '{0}' 속성을 '{2}' 형식에 할당할 수 없습니다.", "Property_0_is_declared_but_its_value_is_never_read_6138": "속성 '{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", "Property_0_is_incompatible_with_index_signature_2530": "'{0}' 속성이 인덱스 시그니처와 호환되지 않습니다.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "암시된 'any' 형식이 있는 식 및 선언에서 오류를 발생합니다.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", - "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언을 제거합니다.", + "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거", + "Replace_import_with_0_95015": "가져오기를 '{0}'(으)로 바꿉니다.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "함수의 일부 코드 경로가 값을 반환하지 않는 경우 오류를 보고합니다.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch 문의 fallthrough case에 대한 오류를 보고합니다.", "Report_errors_in_js_files_8019": ".js 파일의 오류를 보고합니다.", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "내보낸 클래스에 있는 공용 정적 메서드의 반환 형식이 전용 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "이전 프로그램에서 변경되지 않았으므로 '{0}'에서 발생하는 모듈 확인을 다시 사용합니다.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "'{0}' 모듈 확인을 이전 프로그램의 '{1}' 파일에 다시 사용합니다.", - "Rewrite_as_the_indexed_access_type_0_90026": "인덱싱된 액세스 형식 '{0}'(으)로 다시 작성하세요.", + "Rewrite_as_the_indexed_access_type_0_90026": "인덱싱된 액세스 형식 '{0}'(으)로 다시 작성", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "루트 디렉터리를 확인할 수 없어 기본 검색 경로를 건너뜁니다.", "STRATEGY_6039": "전략", "Scoped_package_detected_looking_in_0_6182": "범위가 지정된 패키지가 검색되었습니다. '{0}'에서 찾습니다.", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "소스 맵 옵션", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "특수화된 오버로드 시그니처는 특수화되지 않은 서명에 할당할 수 없습니다.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "동적 가져오기의 지정자는 스프레드 요소일 수 없습니다.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript 대상 버전을 'ES3'(기본값), 'ES5', 'ES2015', 'ES2016', 'ES2017' 또는 'ESNEXT'로 지정합니다.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript 대상 버전을 'ES3'(기본값), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' 또는 'ESNEXT'로 지정합니다.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX 코드 생성 'preserve', 'react-native' 또는 'react'를 지정합니다.", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "컴파일에 포함할 라이브러리 파일 지정: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "모듈 코드 생성을 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' 또는 'ESNext'로 지정합니다.", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "입력 파일의 루트 디렉터리를 지정하세요. --outDir이 포함된 출력 디렉터리 구조를 제어하는 데 사용됩니다.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' 식에서 Spread 연산자는 ECMAScript 5 이상을 대상으로 하는 경우에만 사용할 수 있습니다.", "Spread_types_may_only_be_created_from_object_types_2698": "spread 유형은 개체 형식에서만 만들 수 있습니다.", + "Starting_compilation_in_watch_mode_6031": "감시 모드에서 컴파일을 시작하는 중...", "Statement_expected_1129": "문이 필요합니다.", "Statements_are_not_allowed_in_ambient_contexts_1036": "앰비언트 컨텍스트에서는 문이 허용되지 않습니다.", "Static_members_cannot_reference_class_type_parameters_2302": "정적 멤버는 클래스 형식 매개 변수를 참조할 수 없습니다.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "문자열 리터럴이 필요합니다.", "String_literal_with_double_quotes_expected_1327": "큰따옴표로 묶은 문자열 리터럴이 필요합니다.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "색과 컨텍스트를 사용하여 오류 및 메시지를 스타일화합니다(실험적).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "후속 속성 선언에 같은 형식이 있어야 합니다. '{0}' 속성이 '{1}' 형식이어야 하는데 여기에는 '{2}' 형식이 있습니다.", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "후속 변수 선언에 같은 형식이 있어야 합니다. '{0}' 변수가 '{1}' 형식이어야 하는데 여기에는 '{2}' 형식이 있습니다.", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "'{1}' 패턴에 대한 '{0}' 대체의 형식이 잘못되었습니다. 'string'이 필요한데 '{2}'을(를) 얻었습니다.", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "'{1}' 패턴의 '{0}' 대체에는 '*' 문자를 최대 하나만 사용할 수 있습니다.", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "'{0}' 형식은 배열 형식 또는 문자열 형식이 아니거나, 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "'{0}' 형식은 배열 형식이 아니거나 반복기를 반환하는 '[Symbol.iterator]()' 메서드가 없습니다.", "Type_0_is_not_assignable_to_type_1_2322": "'{0}' 형식은 '{1}' 형식에 할당할 수 없습니다.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "'{0}' 형식을 '{1}' 형식에 할당할 수 없습니다. 이름이 같은 2개의 서로 다른 형식이 있지만 서로 관련은 없습니다.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "'{0}' 형식을 '{1}' 형식에 할당할 수 없습니다. 이름이 같은 2개의 서로 다른 형식이 있지만 서로 관련은 없습니다.", "Type_0_is_not_comparable_to_type_1_2678": "'{0}' 형식을 '{1}' 형식과 비교할 수 없습니다.", "Type_0_is_not_generic_2315": "'{0}' 형식이 제네릭이 아닙니다.", "Type_0_provides_no_match_for_the_signature_1_2658": "'{0}' 형식에서 '{1}' 시그니처에 대한 일치하는 항목을 제공하지 않습니다.", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "종결되지 않은 템플릿 리터럴입니다.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "형식화되지 않은 함수 호출에는 형식 인수를 사용할 수 없습니다.", "Unused_label_7028": "사용되지 않는 레이블입니다.", + "Use_synthetic_default_member_95016": "가상 '기본' 멤버를 사용합니다.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "ECMAScript 5 이상에서만 'for...of' 문에서 문자열을 사용할 수 있습니다.", "VERSION_6036": "버전", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' 형식의 값에 '{1}' 형식과 공통된 속성이 없습니다. 속성을 호출하려고 했습니까?", @@ -913,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "'const' 선언은 초기화해야 합니다.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽에서만 사용할 수 있습니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽 또는 형식 쿼리에서만 사용할 수 있습니다.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations'는 .ts 파일에서만 사용할 수 있습니다.", "export_can_only_be_used_in_a_ts_file_8003": "'export='는 .ts 파일에서만 사용할 수 있습니다.", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions'는 .ts 파일에서만 사용할 수 있습니다.", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations'는 .ts 파일에서만 사용할 수 있습니다.", "types_can_only_be_used_in_a_ts_file_8010": "'types'는 .ts 파일에서만 사용할 수 있습니다.", - "unique_symbol_types_are_not_allowed_here_1335": "여기에서 '고유 기호' 형식은 허용되지 않습니다.", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'고유 기호' 형식은 변수 문의 변수에만 허용됩니다.", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'고유 기호' 형식은 바인딩 이름과 함께 변수 선언에 사용할 수 없습니다.", + "unique_symbol_types_are_not_allowed_here_1335": "여기에서 'unique symbol' 형식은 허용되지 않습니다.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "'unique symbol' 형식은 변수 문의 변수에만 허용됩니다.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "'unique symbol' 형식은 바인딩 이름과 함께 변수 선언에 사용할 수 없습니다.", "with_statements_are_not_allowed_in_an_async_function_block_1300": "'with' 문은 비동기 함수 블록에서 사용할 수 없습니다.", "with_statements_are_not_allowed_in_strict_mode_1101": "'with' 문은 strict 모드에서 사용할 수 없습니다.", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "'yield' 식은 매개 변수 이니셜라이저에서 사용할 수 없습니다." diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 6d3d437bf6dec..0a4a47befb9c9 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -570,7 +570,7 @@ interface Math { */ atan2(y: number, x: number): number; /** - * Returns the smallest number greater than or equal to its numeric argument. + * Returns the smallest integer greater than or equal to its numeric argument. * @param x A numeric expression. */ ceil(x: number): number; @@ -585,7 +585,7 @@ interface Math { */ exp(x: number): number; /** - * Returns the greatest number less than or equal to its numeric argument. + * Returns the greatest integer less than or equal to its numeric argument. * @param x A numeric expression. */ floor(x: number): number; @@ -1012,12 +1012,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1133,12 +1133,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -4879,7 +4879,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -4888,7 +4888,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -5206,7 +5207,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -7714,11 +7715,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -7875,9 +7876,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -9015,6 +9017,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -9318,6 +9321,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -9613,8 +9620,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -10175,6 +10183,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -11076,8 +11085,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11480,10 +11490,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -11652,7 +11662,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -11666,10 +11676,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -11680,8 +11690,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -13281,8 +13291,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -13345,6 +13355,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -16331,7 +16342,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -16419,8 +16430,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -18775,6 +18786,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -18793,6 +18821,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -18897,6 +18944,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -19147,6 +19231,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -19364,7 +19449,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 0c3292a3bbc09..cfacd6cef3f16 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -781,7 +781,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -790,7 +790,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1108,7 +1109,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3616,11 +3617,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3777,9 +3778,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4917,6 +4919,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5220,6 +5223,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5515,8 +5522,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6077,6 +6085,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6978,8 +6987,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7382,10 +7392,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7554,7 +7564,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7568,10 +7578,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7582,8 +7592,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9183,8 +9193,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9247,6 +9257,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12233,7 +12244,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12321,8 +12332,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14677,6 +14688,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14695,6 +14723,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14799,6 +14846,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -15049,6 +15133,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15266,7 +15351,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es2015.collection.d.ts b/lib/lib.es2015.collection.d.ts index 4d84af429be98..84b9ad6c0ef52 100644 --- a/lib/lib.es2015.collection.d.ts +++ b/lib/lib.es2015.collection.d.ts @@ -30,7 +30,7 @@ interface Map { interface MapConstructor { new (): Map; - new (entries?: [K, V][]): Map; + new (entries?: ReadonlyArray<[K, V]>): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -51,7 +51,7 @@ interface WeakMap { interface WeakMapConstructor { new (): WeakMap; - new (entries?: [K, V][]): WeakMap; + new (entries?: ReadonlyArray<[K, V]>): WeakMap; readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -67,7 +67,7 @@ interface Set { interface SetConstructor { new (): Set; - new (values?: T[]): Set; + new (values?: ReadonlyArray): Set; readonly prototype: Set; } declare var Set: SetConstructor; @@ -78,7 +78,7 @@ interface ReadonlySet { readonly size: number; } -interface WeakSet { +interface WeakSet { add(value: T): this; delete(value: T): boolean; has(value: T): boolean; @@ -86,7 +86,7 @@ interface WeakSet { interface WeakSetConstructor { new (): WeakSet; - new (values?: T[]): WeakSet; + new (values?: ReadonlyArray): WeakSet; readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index f1734cedd8bc0..5e2788d2fd1a0 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -138,8 +138,9 @@ interface Math { log1p(x: number): number; /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). + * Returns the result of (e^x - 1), which is an implementation-dependent approximation to + * subtracting 1 from the exponential function of x (e raised to the power of x, where e + * is the base of the natural logarithms). * @param x A numeric expression. */ expm1(x: number): number; diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 16db98d991939..72f20e690eab7 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -72,7 +72,7 @@ interface ArrayConstructor { * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. */ - from(iterable: Iterable): T[]; + from(iterable: Iterable | ArrayLike): T[]; /** * Creates an array from an iterable object. @@ -80,7 +80,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; + from(iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -200,7 +200,7 @@ interface SetConstructor { new (iterable: Iterable): Set; } -interface WeakSet { } +interface WeakSet { } interface WeakSetConstructor { new (iterable: Iterable): WeakSet; diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index 0b97de7157dc4..65ce71cf3e3d9 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -138,7 +138,7 @@ interface Set { readonly [Symbol.toStringTag]: "Set"; } -interface WeakSet { +interface WeakSet { readonly [Symbol.toStringTag]: "WeakSet"; } diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index b8a7dae039d4f..aae287e9082a9 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -784,7 +784,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -793,7 +793,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1111,7 +1112,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3619,11 +3620,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3780,9 +3781,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4920,6 +4922,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5223,6 +5226,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5518,8 +5525,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6080,6 +6088,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6981,8 +6990,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7385,10 +7395,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7557,7 +7567,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7571,10 +7581,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7585,8 +7595,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9186,8 +9196,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9250,6 +9260,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12236,7 +12247,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12324,8 +12335,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14680,6 +14691,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14698,6 +14726,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14802,6 +14849,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -15052,6 +15136,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15269,7 +15354,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 6e021331e37da..a5777d3e8774d 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -789,7 +789,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -798,7 +798,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1116,7 +1117,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3624,11 +3625,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3785,9 +3786,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4925,6 +4927,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5228,6 +5231,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5523,8 +5530,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6085,6 +6093,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6986,8 +6995,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7390,10 +7400,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7562,7 +7572,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7576,10 +7586,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7590,8 +7600,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9191,8 +9201,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9255,6 +9265,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12241,7 +12252,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12329,8 +12340,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14685,6 +14696,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14703,6 +14731,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14807,6 +14854,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -15057,6 +15141,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15274,7 +15359,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es2017.object.d.ts b/lib/lib.es2017.object.d.ts index c0f782464fffb..65aa1f959284c 100644 --- a/lib/lib.es2017.object.d.ts +++ b/lib/lib.es2017.object.d.ts @@ -23,25 +23,25 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: { [s: string]: T } | { [n: number]: T }): T[]; + values(o: { [s: string]: T } | ArrayLike): T[]; /** * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: any): any[]; + values(o: {}): any[]; /** * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: { [s: string]: T } | { [n: number]: T }): [string, T][]; + entries(o: { [s: string]: T } | ArrayLike): [string, T][]; /** * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: any): [string, any][]; + entries(o: {}): [string, any][]; /** * Returns an object containing all own property descriptors of an object diff --git a/lib/lib.es2018.d.ts b/lib/lib.es2018.d.ts index c7ea194ecfde3..820467445eb0c 100644 --- a/lib/lib.es2018.d.ts +++ b/lib/lib.es2018.d.ts @@ -18,4 +18,4 @@ and limitations under the License. /// -/// \ No newline at end of file +/// diff --git a/lib/lib.es2018.full.d.ts b/lib/lib.es2018.full.d.ts index 5333251034adc..28cd49d584693 100644 --- a/lib/lib.es2018.full.d.ts +++ b/lib/lib.es2018.full.d.ts @@ -21,6 +21,7 @@ and limitations under the License. /// + ///////////////////////////// /// DOM APIs ///////////////////////////// @@ -783,7 +784,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -792,7 +793,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1110,7 +1112,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3618,11 +3620,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3779,9 +3781,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4919,6 +4922,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5222,6 +5226,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5517,8 +5525,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6079,6 +6088,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6980,8 +6990,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7384,10 +7395,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7556,7 +7567,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7570,10 +7581,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7584,8 +7595,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9185,8 +9196,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9249,6 +9260,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12235,7 +12247,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12323,8 +12335,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14679,6 +14691,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14697,6 +14726,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14801,6 +14849,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -15051,6 +15136,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15268,7 +15354,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 3f495ed40a92c..35aa9c6101ffe 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -570,7 +570,7 @@ interface Math { */ atan2(y: number, x: number): number; /** - * Returns the smallest number greater than or equal to its numeric argument. + * Returns the smallest integer greater than or equal to its numeric argument. * @param x A numeric expression. */ ceil(x: number): number; @@ -585,7 +585,7 @@ interface Math { */ exp(x: number): number; /** - * Returns the greatest number less than or equal to its numeric argument. + * Returns the greatest integer less than or equal to its numeric argument. * @param x A numeric expression. */ floor(x: number): number; @@ -1012,12 +1012,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1133,12 +1133,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 9d6b6b345fad1..665dad71f184b 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -570,7 +570,7 @@ interface Math { */ atan2(y: number, x: number): number; /** - * Returns the smallest number greater than or equal to its numeric argument. + * Returns the smallest integer greater than or equal to its numeric argument. * @param x A numeric expression. */ ceil(x: number): number; @@ -585,7 +585,7 @@ interface Math { */ exp(x: number): number; /** - * Returns the greatest number less than or equal to its numeric argument. + * Returns the greatest integer less than or equal to its numeric argument. * @param x A numeric expression. */ floor(x: number): number; @@ -1012,12 +1012,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1133,12 +1133,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: ReadonlyArray[]): T[]; + concat(...items: (T[] | ReadonlyArray)[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | ReadonlyArray)[]): T[]; + concat(...items: (T | T[] | ReadonlyArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -4236,8 +4236,9 @@ interface Math { log1p(x: number): number; /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). + * Returns the result of (e^x - 1), which is an implementation-dependent approximation to + * subtracting 1 from the exponential function of x (e raised to the power of x, where e + * is the base of the natural logarithms). * @param x A numeric expression. */ expm1(x: number): number; @@ -4655,7 +4656,7 @@ interface Map { interface MapConstructor { new (): Map; - new (entries?: [K, V][]): Map; + new (entries?: ReadonlyArray<[K, V]>): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -4676,7 +4677,7 @@ interface WeakMap { interface WeakMapConstructor { new (): WeakMap; - new (entries?: [K, V][]): WeakMap; + new (entries?: ReadonlyArray<[K, V]>): WeakMap; readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -4692,7 +4693,7 @@ interface Set { interface SetConstructor { new (): Set; - new (values?: T[]): Set; + new (values?: ReadonlyArray): Set; readonly prototype: Set; } declare var Set: SetConstructor; @@ -4703,7 +4704,7 @@ interface ReadonlySet { readonly size: number; } -interface WeakSet { +interface WeakSet { add(value: T): this; delete(value: T): boolean; has(value: T): boolean; @@ -4711,7 +4712,7 @@ interface WeakSet { interface WeakSetConstructor { new (): WeakSet; - new (values?: T[]): WeakSet; + new (values?: ReadonlyArray): WeakSet; readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; @@ -4825,7 +4826,7 @@ interface ArrayConstructor { * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. */ - from(iterable: Iterable): T[]; + from(iterable: Iterable | ArrayLike): T[]; /** * Creates an array from an iterable object. @@ -4833,7 +4834,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; + from(iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -4953,7 +4954,7 @@ interface SetConstructor { new (iterable: Iterable): Set; } -interface WeakSet { } +interface WeakSet { } interface WeakSetConstructor { new (iterable: Iterable): WeakSet; @@ -5648,7 +5649,7 @@ interface Set { readonly [Symbol.toStringTag]: "Set"; } -interface WeakSet { +interface WeakSet { readonly [Symbol.toStringTag]: "WeakSet"; } @@ -6590,7 +6591,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -6599,7 +6600,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -6917,7 +6919,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -9425,11 +9427,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -9586,9 +9588,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -10726,6 +10729,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11029,6 +11033,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11324,8 +11332,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -11886,6 +11895,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -12787,8 +12797,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -13191,10 +13202,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -13363,7 +13374,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -13377,10 +13388,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -13391,8 +13402,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -14992,8 +15003,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -15056,6 +15067,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -18042,7 +18054,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -18130,8 +18142,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -20486,6 +20498,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -20504,6 +20533,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -20608,6 +20656,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -20858,6 +20943,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -21075,7 +21161,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.esnext.array.d.ts b/lib/lib.esnext.array.d.ts new file mode 100644 index 0000000000000..ce26358d3d6cd --- /dev/null +++ b/lib/lib.esnext.array.d.ts @@ -0,0 +1,223 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface ReadonlyArray { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by a flatten of depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|U[], + thisArg?: This + ): U[] + + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + ReadonlyArray[][]> | + ReadonlyArray[][][]> | + + ReadonlyArray>> | + ReadonlyArray[][]>> | + ReadonlyArray>[][]> | + ReadonlyArray[]>[]> | + ReadonlyArray>[]> | + ReadonlyArray[]>> | + + ReadonlyArray>>> | + ReadonlyArray[]>>> | + ReadonlyArray>[]>> | + ReadonlyArray>>[]> | + + ReadonlyArray>>>>, + depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray[][]> | + ReadonlyArray[]> | + ReadonlyArray> | + + ReadonlyArray>> | + ReadonlyArray[]>> | + ReadonlyArray>[]> | + + ReadonlyArray>>>, + depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + + ReadonlyArray>>, + depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + ReadonlyArray>, + depth?: 1 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray, + depth: 0 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flatten method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flatten(depth?: number): any[]; + } + +interface Array { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by a flatten of depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|U[], + thisArg?: This + ): U[] + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][][][], depth: 7): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][][], depth: 6): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][], depth: 5): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][], depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][], depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][], depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][], depth?: 1): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[], depth: 0): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flatten method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flatten(depth?: number): any[]; +} diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts index ebc1e9d529999..0947f078418e0 100644 --- a/lib/lib.esnext.d.ts +++ b/lib/lib.esnext.d.ts @@ -18,5 +18,7 @@ and limitations under the License. /// -/// +/// /// +/// +/// diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index cb83c656085fc..66dff98d68b39 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -18,8 +18,10 @@ and limitations under the License. /// -/// +/// /// +/// +/// @@ -785,7 +787,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -794,7 +796,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1112,7 +1115,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3620,11 +3623,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3781,9 +3784,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4921,6 +4925,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5224,6 +5229,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5519,8 +5528,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6081,6 +6091,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6982,8 +6993,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7386,10 +7398,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7558,7 +7570,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7572,10 +7584,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7586,8 +7598,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9187,8 +9199,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9251,6 +9263,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12237,7 +12250,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12325,8 +12338,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14681,6 +14694,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14699,6 +14729,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14803,6 +14852,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -15053,6 +15139,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15270,7 +15357,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.esnext.promise.d.ts b/lib/lib.esnext.promise.d.ts new file mode 100644 index 0000000000000..d73b4d4568844 --- /dev/null +++ b/lib/lib.esnext.promise.d.ts @@ -0,0 +1,32 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): Promise +} diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index cf7eea74c3c70..4d76061020e20 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -86,12 +86,13 @@ interface ObjectURLOptions { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -139,7 +140,7 @@ interface NotificationEventInit extends ExtendableEventInit { } interface PushEventInit extends ExtendableEventInit { - data?: any; + data?: BufferSource | USVString; } interface SyncEventInit extends ExtendableEventInit { @@ -434,9 +435,10 @@ declare var EventTarget: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -979,6 +981,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -1081,7 +1084,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -1841,6 +1844,43 @@ interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -1903,7 +1943,7 @@ declare function addEventListener(type: string, listener: EventListenerOrEventLi declare function removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type IDBKeyPath = string; type RequestInfo = Request | string; type USVString = string; diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 03c7be6149bad..610113e43032f 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -12,11 +12,11 @@ "A_class_member_cannot_have_the_0_keyword_1248": "Składowa klasy nie może zawierać słowa kluczowego „{0}”.", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Wyrażenie przecinkowe nie jest dozwolone w obliczonej nazwie właściwości.", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Obliczona nazwa właściwości nie może odwoływać się do parametru typu z zawierającego go typu.", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Nazwa właściwości obliczanej w deklaracji właściwości klasy musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Nazwa właściwości obliczanej w przeciążeniu metody musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Nazwa właściwości obliczanej w typie literału musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Nazwa właściwości obliczanej w otaczającym kontekście musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Nazwa właściwości obliczanej w interfejsie musi odwoływać się do wyrażenia, którego typem jest typ literału lub typ „unikatowy symbol”.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Nazwa właściwości obliczanej w deklaracji właściwości klasy musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Nazwa właściwości obliczanej w przeciążeniu metody musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Nazwa właściwości obliczanej w typie literału musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Nazwa właściwości obliczanej w otaczającym kontekście musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Nazwa właściwości obliczanej w interfejsie musi odwoływać się do wyrażenia, którego typem jest literał lub „unique symbol”.", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Obliczona nazwa właściwości musi być typu „string”, „number”, „symbol” lub „any”.", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Obliczona nazwa właściwości w postaci „{0}” musi być typu „symbol”.", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Dostęp do składowej wyliczenia ze specyfikatorem const można uzyskać tylko za pomocą literału ciągu.", @@ -48,14 +48,15 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklaracja przestrzeni nazw nie może znajdować się w innym pliku niż klasa lub funkcja, z którą ją scalono.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklaracja przestrzeni nazw nie może występować przed klasą lub funkcją, z którą ją scalono.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklaracja przestrzeni nazw jest dozwolona tylko w przestrzeni nazw lub module.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Nie można wywołać lub skonstruować importu stylu przestrzeni nazw. Spowoduje to błąd w czasie wykonania.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicjator parametru jest dozwolony tylko w implementacji funkcji lub konstruktora.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Właściwości parametru nie można zadeklarować za pomocą parametru rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Właściwość parametru jest dozwolona tylko w implementacji konstruktora.", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Właściwości parametru nie można zadeklarować za pomocą wzorca wiązania.", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Ścieżka w opcji „extends” musi być względna lub bezwzględna, lecz element „{0}” nie spełnia tego wymagania.", "A_promise_must_have_a_then_method_1059": "Obietnica musi mieć metodę „then”.", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Właściwość klasy, której typem jest typ „unikatowy symbol”, musi być „static” i „readonly”.", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Właściwość interfejsu lub typu, którego typem jest typ „unikatowy symbol”, musi być „readonly”.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Właściwość klasy, której typem jest „unique symbol”, musi być określona zarówno jako „static”, jak i „readonly”.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Właściwość klasy, której typem jest literał lub „unique symbol”, musi być określona zarówno jako „static”, jak i „readonly”.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Wymagany parametr nie może występować po opcjonalnym parametrze.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Element rest nie może zawierać wzorca wiązania.", "A_rest_element_cannot_have_an_initializer_1186": "Element rest nie może mieć inicjatora.", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Predykat typów nie może zawierać odwołania do elementu „{0}” we wzorcu wiązania.", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Predykat typów jest dozwolony tylko w położeniu zwracanego typu dla funkcji i metod.", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Musi być możliwe przypisanie typu predykatu typów do typu jego parametru.", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Zmienna, której typem jest typ „unikatowy symbol”, musi być „const”.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Zmienna, której typem „unique symbol”, musi być określona jako „const”.", "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.", @@ -91,11 +92,12 @@ "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.", - "Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”.", - "Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”.", - "Add_missing_super_call_90001": "Dodaj brakujące wywołanie „super()”.", - "Add_this_to_unresolved_variable_90008": "Dodaj „this.” do nierozpoznanej zmiennej.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Dodanie pliku tsconfig.json pomoże w organizowaniu projektów, które zawierają pliki TypeScript i JavaScript. Dowiedz się więcej: https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”", + "Add_async_modifier_to_containing_function_90029": "Dodaj modyfikator asynchroniczny do funkcji zawierającej", + "Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”", + "Add_missing_super_call_90001": "Dodaj brakujące wywołanie „super()”", + "Add_this_to_unresolved_variable_90008": "Dodaj „this.” do nierozpoznanej zmiennej", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Dodanie pliku tsconfig.json pomoże w organizowaniu projektów, które zawierają pliki TypeScript i JavaScript. Dowiedz się więcej: https://aka.ms/tsconfig.", "Additional_Checks_6176": "Dodatkowe kontrole", "Advanced_Options_6178": "Opcje zaawansowane", "All_declarations_of_0_must_have_identical_modifiers_2687": "Wszystkie deklaracje elementu „{0}” muszą mieć identyczne modyfikatory.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Parametr sygnatury indeksu nie może mieć modyfikatora dostępności.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Parametr sygnatury indeksu nie może mieć inicjatora.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Parametr sygnatury indeksu musi mieć adnotację typu.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Typ parametru sygnatury indeksu nie może być aliasem typu. Rozważ zastosowanie następującego zapisu: „[{0}: {1}]: {2}”.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Typ parametru sygnatury indeksu nie może być typem unii. Rozważ użycie zamiast niego mapowanego typu obiektu.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr sygnatury indeksu musi być typu „string” lub „number”.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Interfejs może rozszerzać tylko identyfikator/nazwę kwalifikowaną z opcjonalnymi argumentami typu.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Interfejs może rozszerzać tylko klasę lub inny interfejs.", @@ -147,8 +151,8 @@ "An_object_member_cannot_be_declared_optional_1162": "Składowa obiektu nie może być zadeklarowana jako opcjonalna.", "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", + "Annotate_with_type_from_JSDoc_95009": "Dodaj adnotację z typem z danych JSDoc", + "Annotate_with_types_from_JSDoc_95010": "Dodaj adnotację z typami z danych 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}”.", @@ -165,7 +169,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_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}”]”?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Nie można zaimportować plików deklaracji typu. Rozważ zaimportowanie „{0}” zamiast „{1}”.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Nie można zainicjować zmiennej „{0}” z zakresu zewnętrznego w tym samym zakresie co deklaracja „{1}” należąca do zakresu bloku.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nie można wywołać wyrażenia, w którego typie nie ma sygnatury wywołania. Typ „{0}” nie ma zgodnych sygnatur wywołań.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null”.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „null” lub „undefined”.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Nie można wywołać obiektu, który ma prawdopodobnie wartość „undefined”.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Nie można ponownie wyeksportować typu, jeśli podano flagę „--isolatedModules”", "Cannot_read_file_0_Colon_1_5012": "Nie można odczytać pliku „{0}”: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Nie można ponownie zadeklarować zmiennej „{0}” o zakresie bloku.", @@ -210,9 +217,9 @@ "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ń element „{0}” na „{1}”.", - "Change_extends_to_implements_90003": "Zmień atrybut „extends” na „implements”.", - "Change_spelling_to_0_90022": "Zmiana pisowni na „{0}”.", + "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": "Zmień 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}”.", "Circular_definition_of_import_alias_0_2303": "Definicja cykliczna aliasu importu „{0}”.", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Wykryto cykliczność podczas rozpoznawania konfiguracji: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Klasa „{0}” definiuje funkcję składową wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako właściwość składowej wystąpienia.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Klasa „{0}” definiuje właściwość składowej wystąpienia „{1}”, ale rozszerzona klasa „{2}” definiuje ją jako funkcję składową wystąpienia.", "Class_0_incorrectly_extends_base_class_1_2415": "Klasa „{0}” niepoprawnie rozszerza klasę bazową „{1}”.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Klasa „{0}” niepoprawnie implementuje klasę „{1}”. Czy chodziło o rozszerzenie „{1}” i odziedziczenie jego elementów członkowskich jako podklasy?", "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”.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Nie podano pliku zawierającego i nie można określić katalogu głównego. Pomijanie wyszukiwania w folderze „node_modules”.", "Convert_function_0_to_class_95002": "Konwertuj funkcję „{0}” na klasę", "Convert_function_to_an_ES2015_class_95001": "Konwertuj funkcję na klasę ES2015", + "Convert_to_ES6_module_95017": "Konwertuj na moduł ES6", "Convert_to_default_import_95013": "Konwertuj na import domyślny", "Corrupted_locale_file_0_6051": "Uszkodzony plik ustawień regionalnych {0}.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nie można znaleźć pliku deklaracji dla modułu „{0}”. Element „{1}” ma niejawnie typ „any”.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Oczekiwano deklaracji.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Nazwa deklaracji powoduje konflikt z wbudowanym identyfikatorem globalnym „{0}”.", "Declaration_or_statement_expected_1128": "Oczekiwano deklaracji lub instrukcji.", - "Declare_method_0_90023": "Zadeklaruj metodę „{0}”.", - "Declare_property_0_90016": "Zadeklaruj właściwość „{0}”.", - "Declare_static_method_0_90024": "Zadeklaruj metodę statyczną „{0}”.", - "Declare_static_property_0_90027": "Zadeklaruj właściwość statyczną „{0}”.", + "Declare_method_0_90023": "Zadeklaruj metodę „{0}”", + "Declare_property_0_90016": "Zadeklaruj właściwość „{0}”", + "Declare_static_method_0_90024": "Zadeklaruj metodę statyczną „{0}”", + "Declare_static_property_0_90027": "Zadeklaruj właściwość statyczną „{0}”", "Decorators_are_not_valid_here_1206": "Elementy Decorator nie są tutaj prawidłowe.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Nie można stosować elementów Decorator do wielu metod dostępu pobierania/ustawiania o takiej samej nazwie.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Domyślny eksport modułu ma nazwę prywatną „{0}” lub używa tej nazwy.", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Przestarzałe] Użyj w zastępstwie opcji „--skipLibCheck”. Pomiń sprawdzanie typów domyślnych plików deklaracji biblioteki.", "Digit_expected_1124": "Oczekiwano cyfry.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Katalog „{0}” nie istnieje. Operacje wyszukiwania w nim zostaną pominięte.", - "Disable_checking_for_this_file_90018": "Wyłącz sprawdzanie dla tego pliku.", + "Disable_checking_for_this_file_90018": "Wyłącz sprawdzanie dla tego pliku", "Disable_size_limitations_on_JavaScript_projects_6162": "Wyłącz ograniczenia rozmiarów dla projektów JavaScript.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Wyłącz dokładne sprawdzanie sygnatur ogólnych w typach funkcji.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Nie zezwalaj na przywoływanie tego samego pliku za pomocą nazw różniących się wielkością liter.", @@ -309,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Włącz dokładne sprawdzanie inicjowania właściwości w klasach.", "Enable_strict_null_checks_6113": "Włącz dokładne sprawdzanie wartości null.", "Enable_tracing_of_the_name_resolution_process_6085": "Włącz śledzenie procesu rozpoznawania nazw.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Umożliwia współdziałanie emitowania między modułami CommonJS i ES przez tworzenie obiektów przestrzeni nazw dla wszystkich importów. Implikuje użycie ustawienia „allowSyntheticDefaultImports”.", "Enables_experimental_support_for_ES7_async_functions_6068": "Umożliwia obsługę eksperymentalną funkcji asynchronicznych języka ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Umożliwia obsługę eksperymentalną elementów Decorator języka ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Umożliwia obsługę eksperymentalną emitowania metadanych typów elementów Decorator.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Nazwa pliku „{0}” różni się od już dołączonej nazwy pliku „{1}” tylko wielkością liter.", "File_name_0_has_a_1_extension_stripping_it_6132": "Nazwa pliku „{0}” ma rozszerzenie „{1}” — zostanie ono usunięte.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Specyfikacja pliku nie może zawierać katalogu nadrzędnego („..”) wyświetlanego po symbolu wieloznacznym katalogu rekursywnego („**”): „{0}”.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Specyfikacja pliku nie może zawierać wielu cyklicznych symboli wieloznacznych katalogu („**”): „{0}”.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Specyfikacja pliku nie może kończyć się cyklicznym symbolem wieloznacznym katalogu („**”): „{0}”.", "Found_package_json_at_0_6099": "Znaleziono plik „package.json” w lokalizacji „{0}”.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Deklaracje funkcji nie są dozwolone wewnątrz bloków w trybie z ograniczeniami, jeśli elementem docelowym jest „ES3” lub „ES5”.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Oczekiwano identyfikatora. Element „{0}” jest wyrazem zastrzeżonym w trybie z ograniczeniami. Moduły są określane automatycznie w trybie z ograniczeniami.", "Identifier_expected_1003": "Oczekiwano identyfikatora.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Oczekiwano identyfikatora. Ciąg „__esModule” jest zastrzeżony jako eksportowany znacznik podczas transformowania modułów ECMAScript.", - "Ignore_this_error_message_90019": "Ignoruj ten komunikat o błędzie.", - "Implement_inherited_abstract_class_90007": "Implementuj odziedziczoną klasę abstrakcyjną.", - "Implement_interface_0_90006": "Implementuj interfejs „{0}”.", + "Ignore_this_error_message_90019": "Ignoruj ten komunikat o błędzie", + "Implement_inherited_abstract_class_90007": "Wdróż odziedziczoną klasę abstrakcyjną", + "Implement_interface_0_90006": "Implementuj interfejs „{0}”", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Klauzula implements wyeksportowanej klasy „{0}” ma nazwę prywatną „{1}” lub używa tej nazwy.", - "Import_0_from_module_1_90013": "Import „{0}” z modułu „{1}”.", + "Import_0_from_module_1_90013": "Importuj element „{0}” z modułu „{1}”", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Nie można użyć przypisania importu, gdy są używane moduły języka ECMAScript. Zamiast tego rozważ użycie elementu „import * as ns from \"mod\"”, „import {a} from \"mod\"” lub „import d from \"mod\"” albo innego formatu modułu.", "Import_declaration_0_is_using_private_name_1_4000": "Deklaracja importu „{0}” używa nazwy prywatnej „{1}”.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklaracja importu powoduje konflikt z deklaracją lokalną „{0}”.", @@ -424,10 +433,10 @@ "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}”.", + "Infer_parameter_types_from_usage_95012": "Wnioskuj typy parametrów na podstawie użycia", + "Infer_type_of_0_from_usage_95011": "Wnioskuj 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 składowej wystąpienia „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego w konstruktorze.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Inicjator parametru „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego po nim.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Inicjator nie określa żadnej wartości dla tego elementu powiązania, a element powiązania nie ma wartości domyślnej.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Ustawienia regionalne muszą mieć postać lub -. Na przykład „{0}” lub „{1}”.", "Longest_matching_prefix_for_0_is_1_6108": "Najdłuższy zgodny prefiks dla „{0}” to „{1}”.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Wyszukiwanie w folderze „node_modules”, początkowa lokalizacja: „{0}”.", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Ustaw wywołanie „super()” jako pierwszą instrukcję w konstruktorze.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Ustaw wywołanie „super()” jako pierwszą instrukcję w konstruktorze", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Zmapowany typ obiektu niejawnie ma typ szablonu „any”.", "Member_0_implicitly_has_an_1_type_7008": "Dla składowej „{0}” niejawnie określono typ „{1}”.", "Merge_conflict_marker_encountered_1185": "Napotkano znacznik konfliktu scalania.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Scalona deklaracja „{0}” nie może zawierać domyślnej deklaracji eksportu. Rozważ dodanie oddzielnej deklaracji „export default {0}” zamiast niej.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nazwa modułu „{0}” została pomyślnie rozpoznana jako „{1}”. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Rodzaj rozpoznawania modułów nie został podany. Zostanie użyty rodzaj „{0}”.", "Module_resolution_using_rootDirs_has_failed_6111": "Nie można rozpoznać modułów przy użyciu opcji „rootDirs”.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Kolejne następujące po sobie separatory liczbowe nie są dozwolone.", "Multiple_constructor_implementations_are_not_allowed_2392": "Konstruktor nie może mieć wielu implementacji.", "NEWLINE_6061": "NOWY WIERSZ", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Nazwane właściwości „{0}” typów „{1}” i „{2}” nie są identyczne.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Wyrażenie klasy nieabstrakcyjnej nie implementuje odziedziczonej abstrakcyjnej składowej „{0}” z klasy „{1}”.", "Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki kodu zwracają wartość.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Nie można przypisać typu indeksu numerycznego „{0}” do typu indeksu ciągu „{1}”.", + "Numeric_separators_are_not_allowed_here_6188": "Separatory liczbowe nie są dozwolone w tym miejscu.", "Object_is_possibly_null_2531": "Obiekt ma prawdopodobnie wartość „null”.", "Object_is_possibly_null_or_undefined_2533": "Obiekt ma prawdopodobnie wartość „null” lub „undefined”.", "Object_is_possibly_undefined_2532": "Obiekt ma prawdopodobnie wartość „undefined”.", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Typ parametru publicznej statycznej metody ustawiającej „{0}” z wyeksportowanej klasy ma nazwę prywatną „{1}” lub używa tej nazwy.", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analizuj w trybie z ograniczeniami i emituj ciąg „use strict” dla każdego pliku źródłowego.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Wzorzec „{0}” może zawierać maksymalnie jeden znak „*”.", - "Prefix_0_with_an_underscore_90025": "Prefiks „{0}” z podkreśleniem.", + "Prefix_0_with_an_underscore_90025": "Poprzedzaj elementy „{0}” znakiem podkreślenia", "Print_names_of_files_part_of_the_compilation_6155": "Drukuj nazwy plików będących częścią kompilacji.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Drukuj nazwy wygenerowanych plików będących częścią kompilacji.", "Print_the_compiler_s_version_6019": "Wypisz wersję kompilatora.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Właściwość „{0}” nie ma inicjatora i nie jest na pewno przypisana w konstruktorze.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „get” nie ma adnotacji zwracanego typu.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „set” nie ma adnotacji typu parametru.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Właściwości „{0}” w typie „{1}” nie można przypisać do tej samej właściwości w typie podstawowym „{2}”.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Właściwości „{0}” w typie „{1}” nie można przypisać do typu „{2}”.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Właściwość „{0}” jest zadeklarowana, ale jej wartość nie jest nigdy odczytywana.", "Property_0_is_incompatible_with_index_signature_2530": "Właściwość „{0}” jest niezgodna z sygnaturą indeksu.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Zgłaszaj błąd w przypadku wyrażeń i deklaracji z implikowanym typem „any”.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Zgłaszaj błąd w przypadku wyrażeń „this” z niejawnym typem „any”.", "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", - "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”.", + "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”", + "Replace_import_with_0_95015": "Zamień import na element „{0}”.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.", "Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Zwracany typ publicznej metody statycznej z wyeksportowanej klasy ma nazwę prywatną „{0}” lub używa tej nazwy.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Ponownie używane są rozwiązania modułu pochodzące z programu „{0}”, ponieważ rozwiązania nie zmieniły się w stosunku do starej wersji programu.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Ponownie używane jest rozwiązanie modułu „{0}” do pliku „{1}” ze starej wersji programu.", - "Rewrite_as_the_indexed_access_type_0_90026": "Zapisz ponownie jako typ dostępu indeksowanego „{0}”.", + "Rewrite_as_the_indexed_access_type_0_90026": "Napisz ponownie jako indeksowany typ dostępu „{0}”", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Nie można określić katalogu głównego. Pomijanie ścieżek wyszukiwania podstawowego.", "STRATEGY_6039": "STRATEGIA", "Scoped_package_detected_looking_in_0_6182": "Wykryto pakiet w zakresie, wyszukiwanie w „{0}”", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Opcje mapy źródła", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Nie można przypisać specjalizowanej sygnatury przeciążenia do żadnej sygnatury niespecjalizowanej.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Specyfikator dynamicznego importowania nie może być elementem spread.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Podaj wersję docelową języka ECMAScript: „ES3” (domyślna), „ES5”, „ES2015”, „ES2016”, „ES2017” lub „ESNEXT”.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Podaj wersję docelową języka ECMAScript: „ES3” (domyślna), „ES5”, „ES2015”, „ES2016”, „ES2017”, „ES2018” lub „ESNEXT”.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Wybierz sposób generowania kodu JSX: „preserve”, „react-native” lub „react”.", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Określ pliki biblioteki do uwzględnienia w kompilacji: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Określ sposób generowania kodu modułu: „none”, „commonjs”, „amd”, „system”, „umd”, „es2015” lub „ESNext”.", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Określ katalog główny plików wejściowych. Strukturą katalogów wyjściowych można sterować przy użyciu opcji --outDir.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Operator rozpiętości w wyrażeniach „new” jest dostępny tylko wtedy, gdy jest używany język ECMAScript 5 lub nowszy.", "Spread_types_may_only_be_created_from_object_types_2698": "Typy spread można tworzyć tylko z typów obiektu.", + "Starting_compilation_in_watch_mode_6031": "Trwa uruchamianie kompilacji w trybie śledzenia...", "Statement_expected_1129": "Oczekiwano instrukcji.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Instrukcje są niedozwolone w otaczających kontekstach.", "Static_members_cannot_reference_class_type_parameters_2302": "Statyczne składowe nie mogą przywoływać parametrów typu klasy.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Oczekiwano literału ciągu.", "String_literal_with_double_quotes_expected_1327": "Oczekiwano literału ciągu z podwójnymi cudzysłowami.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Stosuj styl dla błędów i komunikatów za pomocą koloru i kontekstu. (eksperymentalne).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Kolejne deklaracje właściwości muszą być tego samego typu. Właściwość „{0}” musi być typu „{1}”, ale w tym miejscu jest typu „{2}”.", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Kolejne deklaracje zmiennej muszą być tego samego typu. Zmienna „{0}” musi być typu „{1}”, ale w tym miejscu jest typu „{2}”.", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Podstawienie „{0}” dla wzorca „{1}” ma nieprawidłowy typ. Oczekiwano typu „string”, a uzyskano typ „{2}”.", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Podstawienie „{0}” we wzorcu „{1}” może zawierać maksymalnie jeden znak „*”.", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "Typ „{0}” nie jest typem tablicy ani ciągu lub nie ma metody „[Symbol.iterator]()” zwracającej iterator.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "Typ „{0}” nie jest typem tablicy lub nie ma metody „[Symbol.iterator]()” zwracającej iterator.", "Type_0_is_not_assignable_to_type_1_2322": "Typu „{0}” nie można przypisać do typu „{1}”.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Typu „{0}” nie można przypisać do typu „{1}”. Istnieją dwa różne typy o tej nazwie, lecz są ze sobą niezwiązane.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Typu „{0}” nie można przypisać do typu „{1}”. Istnieją dwa różne typy o tej nazwie, lecz są ze sobą niezwiązane.", "Type_0_is_not_comparable_to_type_1_2678": "Typu „{0}” nie można porównać z typem „{1}”.", "Type_0_is_not_generic_2315": "Typ „{0}” nie jest ogólny.", "Type_0_provides_no_match_for_the_signature_1_2658": "Typ „{0}” nie udostępnia dopasowania dla sygnatury „{1}”.", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Niezakończony literał szablonu.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Wywołania funkcji bez typu nie mogą przyjmować argumentów typu.", "Unused_label_7028": "Nieużywana etykieta.", + "Use_synthetic_default_member_95016": "Użyj syntetycznej składowej „default”.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Używanie ciągu w instrukcji „for...of” jest obsługiwane tylko w języku ECMAScript 5 lub nowszym.", "VERSION_6036": "WERSJA", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Wartość typu „{0}” nie ma żadnych wspólnych właściwości z typem „{1}”. Czy jej wywołanie było zamierzone?", @@ -913,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Konieczne jest zainicjowanie deklaracji „const”.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest wartość nieskończona.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest niedozwolona wartość „NaN”.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Wyliczenia ze specyfikatorem „const” mogą być używane tylko w wyrażeniach dostępu do indeksu lub właściwości albo po prawej stronie deklaracji importu lub przypisania eksportu.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Wyliczenia ze specyfikatorem „const” mogą być używane tylko w wyrażeniach dostępu do indeksu lub właściwości albo po prawej stronie deklaracji importu, przypisania eksportu lub typu zapytania.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Nie można wywołać elementu „delete” dla identyfikatora w trybie z ograniczeniami.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklaracji wyliczeń można używać tylko w pliku ts.", "export_can_only_be_used_in_a_ts_file_8003": "Ciągu „export=” można użyć tylko w pliku ts.", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Wyrażeń asercji typów można używać tylko w pliku ts.", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Deklaracji parametru typu można używać tylko w pliku ts.", "types_can_only_be_used_in_a_ts_file_8010": "Typów można używać tylko w pliku ts.", - "unique_symbol_types_are_not_allowed_here_1335": "Typy „unikatowy symbol” nie są dozwolone w tym miejscu.", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy „unikatowy symbol” są dozwolone tylko w zmiennych w instrukcji zmiennej.", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typów „unikatowy symbol” nie można używać w deklaracji zmiennej z nazwą powiązania.", + "unique_symbol_types_are_not_allowed_here_1335": "Typy „unique symbol” nie są dozwolone w tym miejscu.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Typy „unique symbol” są dozwolone tylko w zmiennych w instrukcji zmiennej.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Typów „unique symbol” nie można używać w deklaracji zmiennej z nazwą powiązania.", "with_statements_are_not_allowed_in_an_async_function_block_1300": "Instrukcje „with” są niedozwolone w bloku funkcji asynchronicznej.", "with_statements_are_not_allowed_in_strict_mode_1101": "Instrukcje „with” są niedozwolone w trybie z ograniczeniami.", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Wyrażeń „yield” nie można używać w inicjatorze parametru." diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 2bf4ae59f070d..ab61f9213b2bf 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -36,6 +36,7 @@ declare namespace ts.server.protocol { Rename = "rename", Saveto = "saveto", SignatureHelp = "signatureHelp", + Status = "status", TypeDefinition = "typeDefinition", ProjectInfo = "projectInfo", ReloadProjects = "reloadProjects", @@ -48,6 +49,7 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", @@ -137,6 +139,21 @@ declare namespace ts.server.protocol { file: string; projectFileName?: string; } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } /** * Requests a JS Doc comment template for a given position */ @@ -395,6 +412,13 @@ declare namespace ts.server.protocol { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } + interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } interface ApplyCodeActionCommandRequest extends Request { command: CommandTypes.ApplyCodeActionCommand; arguments: ApplyCodeActionCommandRequestArgs; @@ -426,7 +450,15 @@ declare namespace ts.server.protocol { /** * Errorcodes we want to get the fixes for. */ - errorCodes?: number[]; + errorCodes?: ReadonlyArray; + } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; } interface ApplyCodeActionCommandRequestArgs { /** May also be an array of commands. */ @@ -1170,7 +1202,7 @@ declare namespace ts.server.protocol { } interface CodeFixResponse extends Response { /** The code actions that are available */ - body?: CodeAction[]; + body?: CodeFixAction[]; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -1180,6 +1212,17 @@ declare namespace ts.server.protocol { /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ commands?: {}[]; } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray<{}>; + } + interface CodeFixAction extends CodeAction { + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + } /** * Format and format on key response message. */ @@ -1221,6 +1264,11 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ includeExternalModuleExports: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + includeInsertTextCompletions: boolean; } /** * Completions request; value of command field is "completions". @@ -1289,6 +1337,12 @@ declare namespace ts.server.protocol { * is often the same as the name but may be different in certain circumstances. */ sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -1962,6 +2016,7 @@ declare namespace ts.server.protocol { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/pt-BR/diagnosticMessages.generated.json b/lib/pt-BR/diagnosticMessages.generated.json index 37f410337acbf..4ba4b037e247d 100644 --- a/lib/pt-BR/diagnosticMessages.generated.json +++ b/lib/pt-BR/diagnosticMessages.generated.json @@ -12,22 +12,22 @@ "A_class_member_cannot_have_the_0_keyword_1248": "Um membro de classe não pode ter a palavra-chave '{0}'.", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Uma expressão de vírgula não é permitida em um nome de propriedade calculado.", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Um nome de propriedade calculado não pode fazer referência a um parâmetro de tipo no seu tipo recipiente.", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Um nome de propriedade computado em uma declaração de propriedade de classe deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Um nome de propriedade computado em uma sobrecarga do método deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Um nome de propriedade computado em um tipo literal deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Um nome de propriedade computado em um contexto de ambiente deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Um nome de propriedade computado em uma interface deve se referir a uma expressão cujo tipo é um tipo literal ou um 'símbolo exclusivo'.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Um nome de propriedade computado em uma declaração de propriedade de classe deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Um nome de propriedade computado em uma sobrecarga do método deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Um nome de propriedade computado em um tipo literal deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Um nome de propriedade computado em um contexto de ambiente deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Um nome de propriedade computado em uma interface deve se referir a uma expressão cujo tipo é um tipo literal ou um 'unique symbol'.", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Um nome de propriedade calculado deve ser do tipo 'string', 'number', 'symbol' ou 'any'.", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Um nome de propriedade calculado do formulário '{0}' deve ser do tipo 'symbol'.", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Um membro const enum só pode ser acessado usando um literal de cadeia de caracteres.", - "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Um inicializador \"const\" em um contexto de ambiente deve ser uma cadeia ou um literal numérico.", + "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254": "Um inicializador 'const' em um contexto de ambiente deve ser uma cadeia ou um literal numérico.", "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005": "Um construtor não pode conter uma chamada 'super' quando sua classe estende 'null'.", "A_constructor_cannot_have_a_this_parameter_2681": "Um construtor não pode ter um parâmetro 'this'.", "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "Uma instrução 'continue' só pode ser usada em uma instrução de iteração de circunscrição.", "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "Uma instrução 'continue' só pode saltar para um rótulo de uma instrução de iteração de circunscrição.", "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "Um modificador 'declare' não pode ser usado em um contexto de ambiente.", "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": "Um modificador 'declare' é necessário para uma declaração de nível superior em um arquivo .d.ts.", - "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Um decorador pode decoras somente uma implementação de método, não uma sobrecarga.", + "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Um decorador pode decorar somente uma implementação de método, não uma sobrecarga.", "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Uma cláusula 'default' não pode aparecer mais de uma vez em uma instrução 'switch'.", "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Uma exportação padrão só pode ser usada em um módulo do estilo ECMAScript.", "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Uma declaração de atribuição definitiva '!' não é permitida neste contexto.", @@ -42,20 +42,21 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "O gerador não pode ter uma anotação de tipo 'void'.", "A_get_accessor_cannot_have_parameters_1054": "Um acessador 'get' não pode ter parâmetros.", "A_get_accessor_must_return_a_value_2378": "Um acessador 'get' deve retornar um valor.", - "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "O inicializador de um membro em uma declaração enum não pode referenciar membros declarados depois dele, inclusive membros definidos em outros enums.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "O inicializador de um membro em uma declaração de enumeração não pode referenciar membros declarados depois dele, inclusive membros definidos em outras enumerações.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Uma classe mixin deve ter um construtor um único parâmetro rest do tipo 'any[]'.", "A_module_cannot_have_multiple_default_exports_2528": "Um módulo não pode ter várias exportações padrão.", "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Uma declaração de namespace não pode estar em um arquivo diferente de uma classe ou função com a qual ela é mesclada.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Uma declaração de namespace não pode estar localizada antes de uma classe ou função com a qual ela é mesclada.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Uma declaração de namespace só é permitida e um namespace ou módulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Uma importação de estilo do namespace não pode ser chamada nem construída e causará uma falha no tempo de execução.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Um inicializador de parâmetro só é permitido em uma implementação de função ou de construtor.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Uma propriedade de parâmetro não pode ser declarada usando um parâmetro rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Uma propriedade de parâmetro somente é permitida em uma implementação de construtor.", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Uma propriedade de parâmetro pode não ser declarada usando um padrão de associação.", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Um caminho em uma opção 'extends' deve ser relativo ou ter raiz, mas o '{0}' não é.", "A_promise_must_have_a_then_method_1059": "Uma promessa deve ter um método 'then'.", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Uma propriedade de uma classe cujo tipo é um tipo de 'símbolo exclusivo' deve ser 'estática' e 'somente leitura'.", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'símbolo exclusivo' deve ser 'somente leitura'.", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Uma propriedade de uma classe cujo tipo é um tipo de 'unique symbol' deve ser 'static' e 'readonly'.", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'unique symbol' deve ser 'readonly'.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Um parâmetro obrigatório não pode seguir um parâmetro opcional.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Um elemento rest não pode conter um padrão de associação.", "A_rest_element_cannot_have_an_initializer_1186": "Um elemento rest não pode ter um inicializador.", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "O predicado de tipo não pode fazer referência ao elemento '{0}' em um padrão de associação.", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "O predicado de tipo só é permitido na posição de tipo de retorno para funções e métodos.", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "O tipo de um predicado de tipo deve ser atribuível para o tipo de seu parâmetro.", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Uma variável cujo tipo é um tipo de 'símbolo exclusivo' deve ser 'const'.", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Uma variável cujo tipo é um tipo de 'unique symbol' deve ser 'const'.", "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.", @@ -91,11 +92,12 @@ "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.", - "Add_0_to_existing_import_declaration_from_1_90015": "Adicione \"{0}\" à declaração de importação existente de \"{1}\".", - "Add_index_signature_for_property_0_90017": "Adicione assinatura de índice para a propriedade '{0}'.", - "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente.", - "Add_this_to_unresolved_variable_90008": "Adicione 'this.' a uma variável não resolvida.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Adicionar um arquivo tsconfig.json ajuda a organizar projetos que contêm arquivos TypeScript e JavaScript. Saiba mais em https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "Adicionar '{0}' à declaração de importação existente de \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Adicione o modificador assíncrono que contém a função", + "Add_index_signature_for_property_0_90017": "Adicionar assinatura de índice para a propriedade '{0}'", + "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente", + "Add_this_to_unresolved_variable_90008": "Adicionar 'this.' a uma variável não resolvida", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Adicionar um arquivo tsconfig.json ajudará a organizar projetos que contêm arquivos TypeScript e JavaScript. Saiba mais em https://aka.ms/tsconfig.", "Additional_Checks_6176": "Verificações Adicionais", "Advanced_Options_6178": "Opções Avançadas", "All_declarations_of_0_must_have_identical_modifiers_2687": "Todas as declarações de '{0}' devem ter modificadores idênticos.", @@ -111,12 +113,12 @@ "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Um acessador não pode ser declarado em um contexto de ambiente.", "An_accessor_cannot_have_type_parameters_1094": "Um acessador não pode ter parâmetros de tipo.", "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Uma declaração de módulo de ambiente só é permitida no nível superior em um arquivo.", - "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Um operando aritmético deve ser do tipo 'any', 'number' ou um tipo enum.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Um operando aritmético deve ser do tipo 'any', 'number' ou um tipo de enumeração.", "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "Uma função ou método assíncrono em ES5/ES3 requer o construtor 'Promise'. Verifique se você tem a declaração para o construtor 'Promise' ou inclua 'ES2015' em sua opção `--lib`.", "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Um método ou função assíncrona deve ter um tipo de retorno válido que é possível aguardar.", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Um método ou função assíncrona deve retornar uma 'Promessa'. Certifique-se de ter uma declaração para 'Promessa' ou inclua 'ES2015' na sua opção `--lib`.", "An_async_iterator_must_have_a_next_method_2519": "O iterador assíncrono deve ter um método 'next()'.", - "An_enum_member_cannot_have_a_numeric_name_2452": "Um membro enum não pode ter um nome numérico.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Um membro de enumeração não pode ter um nome numérico.", "An_export_assignment_can_only_be_used_in_a_module_1231": "Uma atribuição de exportação só pode ser usada em um módulo.", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Uma atribuição de exportação não pode ser usada em um módulo com outros elementos exportados.", "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Uma atribuição de exportação não pode ser usada em um namespace.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Um parâmetro de assinatura de índice não pode ter um modificador de acessibilidade.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Um parâmetro de assinatura de índice não pode ter um inicializador.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Um parâmetro de assinatura de índice deve ter uma anotação de tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Um tipo de parâmetro de assinatura de índice não pode ser um alias de tipo. Considere gravar ' [{0}: {1}]: {2}' em vez disso.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Um tipo de parâmetro de assinatura de índice não pode ser um tipo de união. Considere usar um tipo de objeto mapeado em vez disso.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Um tipo de parâmetro de assinatura de índice deve ser 'string' ou 'number'.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Uma interface só pode estender um identificador/nome qualificado com argumentos de tipo opcionais.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Uma interface só pode estender uma classe ou outra interface.", @@ -165,7 +169,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_decorator_expression_90028": "Chamar expressão do decorador", "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}\"]'?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Não é possível importar arquivos de declaração de tipo. Considere a possibilidade de importar '{0}' em vez de '{1}'.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Não é possível inicializar a variável com escopo externo '{0}' no mesmo escopo que a declaração de escopo de bloco '{1}'.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Não é possível invocar uma expressão cujo tipo não tem uma assinatura de chamada. O tipo '{0}' não tem assinaturas de chamada compatíveis.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Não é possível invocar um objeto que é possivelmente 'nulo'.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Não é possível invocar um objeto que é possivelmente 'nulo' ou 'indefinido'.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Não é possível invocar um objeto que é possivelmente 'indefinido'.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Não será possível reexportar um tipo quando o sinalizador '--isolatedModules' for fornecido.", "Cannot_read_file_0_Colon_1_5012": "Não é possível ler o arquivo '{0}': {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Não é possível declarar novamente a variável de escopo de bloco '{0}'.", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "Altere 'extends' para 'implements'.", - "Change_spelling_to_0_90022": "Alterar ortografia para '{0}'.", + "Change_0_to_1_90014": "Alterar '{0}' para '{1}'", + "Change_extends_to_implements_90003": "Alterar '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}'.", "Circular_definition_of_import_alias_0_2303": "Definição circular do alias de importação '{0}'.", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Circularidade detectada ao resolver a configuração: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "A classe '{0}' define a função de membro de instância '{1}', mas a classe estendida '{2}' a define como uma propriedade de membro de instância.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "A classe '{0}' define a propriedade de membro de instância '{1}', mas a classe estendida '{2}' a define como uma função de membro de instância.", "Class_0_incorrectly_extends_base_class_1_2415": "A classe '{0}' estende incorretamente a classe base '{1}'.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "A classe '{0}' implementa incorretamente a classe '{1}'. Você pretendia estender '{1}' e herdar seus membros como uma subclasse?", "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`.", @@ -234,7 +242,7 @@ "Compiler_option_0_expects_an_argument_6044": "A opção do compilador '{0}' espera um argumento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "A opção do compilador '{0}' requer um valor do tipo {1}.", "Computed_property_names_are_not_allowed_in_enums_1164": "Nomes de propriedade calculados não são permitidos em enums.", - "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Os valores computados não são permitidos em um enum com membros de valor de cadeia de caracteres.", + "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Os valores computados não são permitidos em uma enumeração com membros de valor de cadeia de caracteres.", "Concatenate_and_emit_output_to_single_file_6001": "Concatenar e emitir saída para um arquivo único.", "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Foram encontradas definições em conflito para '{0}' em '{1}' e em '{2}'. Considere instalar uma versão específica desta biblioteca para solucionar o conflito.", "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Assinatura de constructo, que não tem a anotação de tipo de retorno, implicitamente tem um tipo de retorno 'any'.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "O arquivo contido não foi especificado e o diretório raiz não pode ser determinado, ignorando a pesquisa na pasta 'node_modules'.", "Convert_function_0_to_class_95002": "Converter função '{0}' em classe", "Convert_function_to_an_ES2015_class_95001": "Converter função em uma classe ES2015", + "Convert_to_ES6_module_95017": "Converter em módulo ES6", "Convert_to_default_import_95013": "Converter para importação padrão", "Corrupted_locale_file_0_6051": "Arquivo de localidade {0} corrompido.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Não foi possível localizar o arquivo de declaração para o módulo '{0}'. '{1}' tem implicitamente um tipo 'any'.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Declaração esperada.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "O nome de declaração entra em conflito com o identificador global integrado '{0}'.", "Declaration_or_statement_expected_1128": "Declaração ou instrução esperada.", - "Declare_method_0_90023": "Declare o método '{0}'.", - "Declare_property_0_90016": "Declare a propriedade '{0}'.", - "Declare_static_method_0_90024": "Declare o método estático '{0}'.", - "Declare_static_property_0_90027": "Declare a propriedade estática \"{0}\".", + "Declare_method_0_90023": "Declarar método '{0}'", + "Declare_property_0_90016": "Declarar propriedade '{0}'", + "Declare_static_method_0_90024": "Declarar método estático '{0}'", + "Declare_static_property_0_90027": "Declarar propriedade estática '{0}'", "Decorators_are_not_valid_here_1206": "Os decoradores não são válidos aqui.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Os decoradores não podem ser aplicados a vários acessadores get/set de mesmo nome.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "A exportação padrão do módulo tem ou está usando o nome particular '{0}'.", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Preterido] Use '--skipLibCheck' no lugar. Ignore a verificação de tipo dos arquivos de declaração de biblioteca padrão.", "Digit_expected_1124": "Dígito esperado.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "O diretório '{0}' não existe; ignorando todas as pesquisas nele.", - "Disable_checking_for_this_file_90018": "Desabilitar a verificação para esse arquivo.", + "Disable_checking_for_this_file_90018": "Desabilitar a verificação para esse arquivo", "Disable_size_limitations_on_JavaScript_projects_6162": "Desabilitar as limitações de tamanho nos projetos JavaScript.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Desabilitar verificação estrita de assinaturas genéricas em tipos de função.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Não permitir referências com maiúsculas de minúsculas inconsistentes no mesmo arquivo.", @@ -309,15 +318,16 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Habilite a verificação estrita de inicialização de propriedade nas classes.", "Enable_strict_null_checks_6113": "Habilite verificações nulas estritas.", "Enable_tracing_of_the_name_resolution_process_6085": "Habilite o rastreio do processo de resolução de nome.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Permite emissão de interoperabilidade entre CommonJS e Módulos ES através da criação de objetos de namespace para todas as importações. Implica em 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita o suporte experimental para funções assíncronas de ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", - "Enum_0_used_before_its_declaration_2450": "Enum '{0}' usada antes de sua declaração.", - "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações enum devem ser const ou não const.", - "Enum_member_expected_1132": "Membro enum esperado.", - "Enum_member_must_have_initializer_1061": "O membro enum deve ter um inicializador.", - "Enum_name_cannot_be_0_2431": "O nome de enum não pode ser '{0}'.", - "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "O tipo Enum '{0}' tem membros com inicializadores que não são literais.", + "Enum_0_used_before_its_declaration_2450": "A enumeração '{0}' usada antes de sua declaração.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.", + "Enum_member_expected_1132": "Membro de enumeração esperado.", + "Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.", + "Enum_name_cannot_be_0_2431": "O nome de enumeração não pode ser '{0}'.", + "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "O tipo de Enumeração '{0}' tem membros com inicializadores que não são literais.", "Examples_Colon_0_6026": "Exemplos: {0}", "Excessive_stack_depth_comparing_types_0_and_1_2321": "Profundidade da pilha excessiva ao comparar tipos '{0}' e '{1}'.", "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "Espera-se {0}-{1} argumentos de tipo; forneça esses recursos com uma marca \"@extends\".", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "O nome do arquivo '{0}' difere do nome de arquivo '{1}' já incluído somente em maiúsculas e minúsculas.", "File_name_0_has_a_1_extension_stripping_it_6132": "O nome do arquivo '{0}' tem uma extensão '{1}' – remoção.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "A especificação de arquivo não pode conter um diretório pai ('..') que aparece após um curinga de diretório recursivo ('**'): '{0}'.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "A especificação de arquivo não pode conter vários curingas do diretório recursivo ('**'): '{0}'.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "A especificação de arquivo não pode terminar em um curinga do diretório recursivo ('**'): '{0}'.", "Found_package_json_at_0_6099": "'package.json' encontrado em '{0}'.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Decorações de função não são permitidas dentro de blocos em modo estrito quando o objetivo é 'ES3' ou 'ES5'.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Identificador esperado. '{0}' é uma palavra reservada em modo estrito. Os módulos ficam automaticamente em modo estrito.", "Identifier_expected_1003": "Identificador esperado.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Identificador esperado. '__esModule' é reservado como um marcador exportado ao transformar os módulos ECMAScript.", - "Ignore_this_error_message_90019": "Ignore essa mensagem de erro.", - "Implement_inherited_abstract_class_90007": "Implemente a classe abstrata herdada.", - "Implement_interface_0_90006": "Implemente a interface '{0}'.", + "Ignore_this_error_message_90019": "Ignorar essa mensagem de erro", + "Implement_inherited_abstract_class_90007": "Implementar classe abstrata herdada", + "Implement_interface_0_90006": "Implementar a interface '{0}'", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "A cláusula implements da classe exportada '{0}' tem ou está usando o nome particular '{1}'.", - "Import_0_from_module_1_90013": "Importar '{0}' do módulo \"{1}\".", + "Import_0_from_module_1_90013": "Importar '{0}' do módulo \"{1}\"", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Não é possível usar a atribuição de importação durante o direcionamento para módulos de ECMAScript. Use 'importar * como ns de \"mod\"', 'importar {a} de \"mod\"', 'importar d de \"mod\"' ou outro formato de módulo em vez disso.", "Import_declaration_0_is_using_private_name_1_4000": "A declaração da importação '{0}' está usando o nome particular '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "A declaração da importação está em conflito com a declaração local '{0}'.", @@ -417,17 +426,17 @@ "Import_name_cannot_be_0_2438": "O nome da importação não pode ser '{0}'.", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "A declaração de importação e exportação em uma declaração de módulo de ambiente não pode fazer referência ao módulo por meio do nome do módulo relativo.", "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Importações não são permitidas em acréscimos de módulo. Considere movê-las para o módulo externo delimitador.", - "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Em declarações enum de ambiente, o inicializador de membro deve ser uma expressão de constante.", - "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Em um enum com várias declarações, somente uma declaração pode omitir um inicializador para o primeiro elemento enum.", - "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Em declarações enum 'const', o inicializador de membro deve ser uma expressão de constante.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Em declarações de enumeração de ambiente, o inicializador de membro deve ser uma expressão de constante.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Em uma enumeração com várias declarações, somente uma declaração pode omitir um inicializador para o primeiro elemento de enumeração.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "Em declarações de enumeração 'const', o inicializador de membro deve ser uma expressão de constante.", "Index_signature_in_type_0_only_permits_reading_2542": "Assinatura de índice no tipo '{0}' permite somente leitura.", "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}'.", + "Infer_parameter_types_from_usage_95012": "Inferir tipos de parâmetro pelo uso", + "Infer_type_of_0_from_usage_95011": "Inferir tipo de '{0}' pelo 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.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "O inicializador do parâmetro '{0}' não pode referenciar o identificador '{1}' declarado depois dele.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "O inicializador não fornece um valor para esse elemento de associação e o elemento de associação não tem valor padrão.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "A localidade deve estar no formato ou -. Por exemplo '{0}' ou '{1}'.", "Longest_matching_prefix_for_0_is_1_6108": "O maior prefixo correspondente para '{0}' é '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Pesquisando na pasta 'node_modules', local inicial '{0}'.", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Tornar a chamada 'super()' a primeira instrução no construtor.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Tornar a chamada 'super()' a primeira instrução no construtor", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "O tipo de objeto mapeado implicitamente tem um tipo de modelo 'any'.", "Member_0_implicitly_has_an_1_type_7008": "O membro '{0}' implicitamente tem um tipo '{1}'.", "Merge_conflict_marker_encountered_1185": "Marcador de conflito de mesclagem encontrado.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "A declaração mesclada '{0}' não pode conter uma declaração de exportação padrão. Considere adicionar uma declaração 'export default {0}' independente.", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Nome do módulo '{0}' foi resolvido com sucesso '{1}'. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Resolução de tipo não foi especificado, usando '{0}'.", "Module_resolution_using_rootDirs_has_failed_6111": "Falha na resolução de módulo usando 'rootDirs'.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Não são permitidos vários separadores numéricos consecutivos.", "Multiple_constructor_implementations_are_not_allowed_2392": "Não são permitidas várias implementações de construtor.", "NEWLINE_6061": "NEWLINE", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "As propriedades com nome '{0}' dos tipos '{1}' e '{2}' não são idênticas.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "A expressão da classe não abstrata não implementa o membro abstrato herdado '{0}' da classe '{1}'.", "Not_all_code_paths_return_a_value_7030": "Nem todos os caminhos de código retornam um valor.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "O tipo de índice numérico '{0}' não é atribuível ao tipo de índice de cadeia de caracteres '{1}'.", + "Numeric_separators_are_not_allowed_here_6188": "Separadores numéricos não são permitidos aqui.", "Object_is_possibly_null_2531": "Possivelmente, o objeto é 'nulo'.", "Object_is_possibly_null_or_undefined_2533": "Possivelmente, o objeto é 'nulo' ou 'indefinido'.", "Object_is_possibly_undefined_2532": "Possivelmente, o objeto é 'nulo'.", @@ -584,18 +596,19 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "O tipo de parâmetro do setter estático público '{0}' da classe exportada tem ou está usando o nome privado '{1}'.", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Analisar em modo estrito e emitir \"usar estrito\" para cada arquivo de origem.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "O padrão '{0}' pode ter no máximo um caractere '*'.", - "Prefix_0_with_an_underscore_90025": "Prefixo '{0}' com um sublinhado.", + "Prefix_0_with_an_underscore_90025": "Prefixo '{0}' com um sublinhado", "Print_names_of_files_part_of_the_compilation_6155": "Nomes de impressão das partes dos arquivos da compilação.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Nomes de impressão das partes dos arquivos gerados da compilação.", "Print_the_compiler_s_version_6019": "Imprima a versão do compilador.", "Print_this_message_6017": "Imprima esta mensagem.", - "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe no enum 'const' '{1}'.", + "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "A propriedade '{0}' não existe no tipo '{1}'. Você quis dizer '{2}'?", "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "A propriedade '{0}' tem declarações conflitantes e é inacessível no tipo '{1}'.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "A propriedade '{0}' não tem nenhum inicializador e não está definitivamente atribuída no construtor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador get não tem uma anotação de tipo de retorno.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador set não tem uma anotação de tipo de parâmetro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída à mesma propriedade no tipo base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída ao tipo '{2}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "A propriedade '{0}' é declarada, mas seu valor nunca é lido.", "Property_0_is_incompatible_with_index_signature_2530": "A propriedade '{0}' é incompatível com a assinatura de índice.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Gerar erro em expressões e declarações com um tipo 'any' implícito.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Gerar erro em expressões 'this' com um tipo 'any' implícito.", "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", - "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'.", + "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", + "Replace_import_with_0_95015": "Substitua a importação com '{0}'.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Relate erro quando nem todos os caminhos de código na função retornarem um valor.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Relate erros para casos de fallthrough na instrução switch.", "Report_errors_in_js_files_8019": "Relatar erros em arquivos .js.", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "O tipo de retorno do método estático público da classe exportada tem ou está usando o nome particular '{0}'.", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Reutilizando resoluções de módulo originados em '{0}', já que as resoluções do programa antigo estão inalteradas.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Reutilizando a resolução do módulo '{0}' para o arquivo '{1}' do programa antigo.", - "Rewrite_as_the_indexed_access_type_0_90026": "Regravar como o tipo de acesso indexado '{0}'.", + "Rewrite_as_the_indexed_access_type_0_90026": "Reescrever como o tipo de acesso indexado '{0}'", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Diretório raiz não pode ser determinado, ignorando caminhos de pesquisa primários.", "STRATEGY_6039": "ESTRATÉGIA", "Scoped_package_detected_looking_in_0_6182": "Pacote com escopo detectado, procurando no '{0}'", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Opções do Sourcemap", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "A assinatura de sobrecarga especializada não pode ser atribuída a qualquer assinatura não especializada.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "O especificador de importação dinâmica não pode ser o elemento de difusão.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Especifique a versão de destino do ECMAScript: 'ES3' (padrão), 'ES5', 'ES2015', 'ES2016', 'ES2017' ou 'ESNEXT'.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Especifique a versão de destino do ECMAScript: 'ES3' (padrão), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' ou 'ESNEXT'.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Especifique a geração de código JSX: 'preserve', 'react-native' ou 'react'.", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Especifique os arquivos de biblioteca a serem incluídos na compilação: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Especifique a geração de código de módulo: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' ou 'ESNext'.", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Especifique o diretório raiz de arquivos de entrada. Use para controlar a estrutura do diretório de saída com --outDir.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "O operador de espalhamento só está disponível em expressões 'new' no direcionamento a ECMAScript 5 e superior.", "Spread_types_may_only_be_created_from_object_types_2698": "Os tipos de espalhamento podem ser criados apenas de tipos de objeto.", + "Starting_compilation_in_watch_mode_6031": "Iniciando compilação no modo de inspeção...", "Statement_expected_1129": "Instrução esperada.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Instruções não são permitidas em contextos de ambiente.", "Static_members_cannot_reference_class_type_parameters_2302": "Membros estáticos não podem fazer referência a parâmetros de tipo de classe.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Literal de cadeia de caracteres esperado.", "String_literal_with_double_quotes_expected_1327": "Literal de cadeia com aspas duplas é esperado.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Estilizar erros e mensagens usando cor e contexto (experimental).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Declarações de propriedade subsequentes devem ter o mesmo tipo. A propriedade '{0}' deve ser do tipo '{1}', mas aqui tem o tipo '{2}'.", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Declarações de variável subsequentes devem ter o mesmo tipo. A variável '{0}' deve ser do tipo '{1}', mas aqui tem o tipo '{2}'.", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "A substituição '{0}' para o padrão '{1}' tem um tipo incorreto, 'string' esperada, obteve '{2}'.", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "A substituição '{0}' no padrão '{1}' pode ter no máximo um caractere '*'.", @@ -745,7 +760,7 @@ "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "O lado esquerdo de uma instrução de 'for...in' deve ser do tipo 'string' ou 'any'.", "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "O lado esquerdo de uma instrução 'for...of' não pode usar uma anotação de tipo.", "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "O lado esquerdo de uma instrução 'for...of' deve ser uma variável ou um acesso à propriedade.", - "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "O lado esquerdo de uma operação aritmética deve ser do tipo 'any', 'number' ou enum.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "O lado esquerdo de uma operação aritmética deve ser do tipo 'any', 'number' ou de enumeração.", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "O lado esquerdo de uma expressão de atribuição deve ser uma variável ou um acesso à propriedade.", "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "O lado esquerdo de uma expressão 'in' deve ser do tipo 'any', 'string', 'number' ou 'symbol'.", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "O lado esquerdo de uma expressão 'instanceof' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", @@ -760,7 +775,7 @@ "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "O tipo de retorno de uma função assíncrona deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "O tipo de retorno de uma função assíncrona ou método deve ser o tipo Promessa global.", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "O lado direito de uma instrução 'for...in' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", - "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "O lado direito de uma operação aritmética deve ser do tipo 'any', 'number' ou enum.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "O lado direito de uma operação aritmética deve ser do tipo 'any', 'number' ou de enumeração.", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "O lado direito de uma expressão 'in' deve ser do tipo 'any', um tipo de objeto ou um parâmetro de tipo.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "O lado direito de uma expressão 'instanceof' deve ser do tipo 'any' ou de um tipo que pode ser atribuído ao tipo de interface 'Function'.", "The_specified_path_does_not_exist_Colon_0_5058": "O caminho especificado não existe: '{0}'.", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "O tipo '{0}' não é um tipo de matriz de um tipo de cadeia ou não tem um método '[Symbol.iterator]()' que retorna um iterador.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "O tipo '{0}' não é um tipo de matriz ou não tem um método '[Symbol.iterator]()' que retorna um iterador.", "Type_0_is_not_assignable_to_type_1_2322": "O tipo '{0}' não pode ser atribuído ao tipo '{1}'.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "O tipo '{0}' não é atribuível ao tipo '{1}'. Dois tipos diferentes com esse nome existem, mas eles não são relacionados.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "O tipo '{0}' não é atribuível ao tipo '{1}'. Dois tipos diferentes com esse nome existem, mas eles não estão relacionados.", "Type_0_is_not_comparable_to_type_1_2678": "O tipo '{0}' não pode ser comparável ao tipo '{1}'.", "Type_0_is_not_generic_2315": "O tipo '{0}' não é genérico.", "Type_0_provides_no_match_for_the_signature_1_2658": "O tipo '{0}' fornece nenhuma correspondência para a assinatura '{1}'.", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Literal de modelo não finalizado.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Chamadas de função não tipadas não podem aceitar argumentos de tipo.", "Unused_label_7028": "Rótulo não utilizado.", + "Use_synthetic_default_member_95016": "Use o membro sintético 'padrão'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Há suporte para o uso de uma cadeia de caracteres em uma instrução 'for...of' somente no ECMAScript 5 e superior.", "VERSION_6036": "VERSÃO", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "O valor do tipo '{0}' não tem propriedades em comum com o tipo '{1}'. Você queria chamá-lo?", @@ -909,11 +925,11 @@ "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' só pode ser usado em uma propriedade literal de objeto dentro de uma atribuição de desestruturação.", "case_or_default_expected_1130": "'case' ou 'default' esperado.", "class_expressions_are_not_currently_supported_9003": "No momento, não há suporte para expressões 'class'.", - "const_declarations_can_only_be_declared_inside_a_block_1156": "declarações 'const' só podem ser declaradas dentro de um bloco.", - "const_declarations_must_be_initialized_1155": "As declarações 'const' devem ser inicializadas.", - "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "O inicializador de membro enum 'const' foi avaliado como um valor não finito.", - "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "O inicializador de membro enum 'const' foi avaliado como o valor não permitido 'NaN'.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Enums 'const' só podem ser usados em expressões de acesso de índice ou propriedade, ou do lado direito de uma declaração de importação ou atribuição de exportação.", + "const_declarations_can_only_be_declared_inside_a_block_1156": "Declarações 'const' só podem ser declaradas dentro de um bloco.", + "const_declarations_must_be_initialized_1155": "Declarações 'const' devem ser inicializadas.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "O inicializador de membro de enumeração 'const' foi avaliado como um valor não finito.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "O inicializador de membro de enumeração 'const' foi avaliado como o valor não permitido 'NaN'.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Enumerações 'const' só podem ser usadas em expressões de acesso de índice ou propriedade, ou então do lado direito de uma consulta de tipo, declaração de importação ou atribuição de exportação.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' não pode ser chamado em um identificador no modo estrito.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' só podem ser usadas em um arquivo .ts.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' só pode ser usado em um arquivo .ts.", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "'type assertion expressions' só podem ser usadas em um arquivo .ts.", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "'type parameter declarations' só podem ser usadas em um arquivo .ts.", "types_can_only_be_used_in_a_ts_file_8010": "'types' só podem ser usados em um arquivo .ts.", - "unique_symbol_types_are_not_allowed_here_1335": "tipos de 'símbolo exclusivo' não são permitidos aqui.", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "tipos de 'símbolo exclusivo' são permitidos apenas em variáveis em uma declaração de variável.", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "tipos de 'símbolo exclusivo' não podem ser usados em uma declaração de variável com um nome associado.", + "unique_symbol_types_are_not_allowed_here_1335": "Tipos de 'unique symbol' não são permitidos aqui.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Tipos de 'unique symbol' são permitidos apenas em variáveis em uma declaração de variável.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Tipos de 'unique symbol' não podem ser usados em uma declaração de variável com um nome associado.", "with_statements_are_not_allowed_in_an_async_function_block_1300": "As declarações 'with' não são permitidas em blocos de funções assíncronas.", "with_statements_are_not_allowed_in_strict_mode_1101": "Instruções 'with' não são permitidas no modo estrito.", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "As expressões 'yield' não podem ser usadas em inicializadores de parâmetros." diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index 87c1a2224221d..b0c8e703c15f9 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -12,11 +12,11 @@ "A_class_member_cannot_have_the_0_keyword_1248": "Элемент класса не может иметь ключевое слово \"{0}\".", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "Выражение с запятой запрещено в имени вычисляемого свойства.", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "Имя вычисляемого свойства не может ссылаться на параметр типа из содержащего его типа.", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Имя вычисляемого свойства в объявлении свойств класса должно ссылаться на выражение, тип которого — литерал или уникальный символ.", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Имя вычисляемого свойства в перегрузке метода должно ссылаться на выражение, тип которого — литерал или уникальный символ.", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Имя вычисляемого свойства в литерале должно ссылаться на выражение, тип которого — литерал или уникальный символ.", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Имя вычисляемого свойства в окружающем контексте должно ссылаться на выражение, тип которого — литерал или уникальный символ.", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Имя вычисляемого свойства в интерфейсе должно ссылаться на выражение, тип которого — литерал или уникальный символ.", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "Имя вычисляемого свойства в объявлении свойств класса должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "Имя вычисляемого свойства в перегрузке метода должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "Имя вычисляемого свойства в литерале должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "Имя вычисляемого свойства в окружающем контексте должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "Имя вычисляемого свойства в интерфейсе должно ссылаться на выражение, тип которого — литерал или \"unique symbol\".", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "Имя вычисляемого свойства должно иметь тип string, number, symbol или any.", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "Имя вычисляемого свойства в форме \"{0}\" должно иметь тип symbol.", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "Доступ к элементу перечисления констант может осуществляться только с использованием строкового литерала.", @@ -48,14 +48,15 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Объявление пространства имен и класс или функция, с которыми оно объединено, не могут находится в разных файлах.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Объявление пространства имен не может располагаться раньше класса или функции, с которыми оно объединено.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Объявление пространства имен разрешено использовать только в пространстве имен или модуле.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Импорт стиля пространства имен не может быть вызван или создан и приведет к сбою во время выполнения.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Инициализатор параметра разрешено использовать только в реализации функции или конструктора.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Свойство параметра невозможно объявить с помощью параметра REST.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Свойство параметра допускается только в реализации конструктора.", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "Свойство параметра невозможно объявить с помощью шаблона привязки.", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "Путь в параметре extends должен быть относительным или указанным от корня, но \"{0}\" не является ни тем ни другим.", "A_promise_must_have_a_then_method_1059": "Класс promise должен содержать метод then.", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Свойство класса, тип которого — уникальный символ, должно быть задано как \"static\" и \"readonly\".", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Свойство интерфейса или литерала, тип которого — уникальный символ, должно быть задано как \"readonly\".", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "Свойство класса, тип которого — \"unique symbol\", должно быть задано как \"static\" и \"readonly\".", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Свойство интерфейса или литерала, тип которого — \"unique symbol\", должно быть задано как \"readonly\".", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Обязательный параметр не должен следовать за необязательным.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Элемент rest не может содержать шаблон привязки.", "A_rest_element_cannot_have_an_initializer_1186": "Элемент rest не может содержать инициализатор.", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "Предикат типов не может ссылаться на элемент \"{0}\" в шаблоне привязки.", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "Предикат типов разрешено использовать только в позиции типа возвращаемого значения для функций и методов.", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "Тип предиката типа должен быть доступным для назначения этому типу параметра.", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Переменная типа \"уникальный символ\" должна быть задана как \"const\".", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "Переменная, тип которой — \"unique symbol\", должна быть задана как \"const\".", "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": "Абстрактные методы могут использоваться только в абстрактных классах.", @@ -91,11 +92,12 @@ "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": "Методы доступа должны быть абстрактными или неабстрактными.", - "Add_0_to_existing_import_declaration_from_1_90015": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\".", - "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\".", - "Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\".", - "Add_this_to_unresolved_variable_90008": "Добавление \"this.\" к неразрешенной переменной.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Добавление файла tsconfig.json поможет организовать проекты, содержащие файлы TypeScript и JavaScript. Дополнительные сведения: https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию", + "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", + "Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\"", + "Add_this_to_unresolved_variable_90008": "Добавьте \"this.\" к неразрешенной переменной", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Добавление файла tsconfig.json поможет организовать проекты, содержащие файлы TypeScript и JavaScript. Дополнительные сведения: https://aka.ms/tsconfig.", "Additional_Checks_6176": "Дополнительные проверки", "Advanced_Options_6178": "Дополнительные параметры", "All_declarations_of_0_must_have_identical_modifiers_2687": "Все объявления \"{0}\" должны иметь одинаковые модификаторы.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Параметра сигнатуры индекса не может содержать модификатор специальных возможностей.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Параметр сигнатуры индекса не может содержать инициализатор.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "У параметра сигнатуры индекса должна быть аннотация типа.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Тип параметра сигнатуры индекса не может быть псевдонимом типа. Вместо этого рекомендуется написать \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Тип параметра сигнатуры индекса не может быть типом объединения. Рекомендуется использовать тип сопоставляемого объекта.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Параметр сигнатуры индекса должен иметь тип string или number.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Интерфейс может расширить только идентификатор или полное имя с дополнительными аргументами типа.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Интерфейс может расширять только класс или другой интерфейс.", @@ -165,7 +169,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_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}\"]?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Невозможно импортировать файлы объявления типа. Рекомендуется импортировать \"{0}\" вместо \"{1}\".", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Невозможно инициализировать переменную \"{0}\" с внешней областью видимости в той же области видимости, что и объявление \"{1}\" с областью видимости \"Блок\".", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Не удается вызвать выражение, в типе которого отсутствует сигнатура вызова. Тип \"{0}\" не содержит совместимые сигнатуры вызова.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Не удается вызвать объект, который может иметь значение \"NULL\".", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Не удается вызвать объект, который может иметь значение \"NULL\" или \"undefined\".", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Не удается вызвать объект, который может иметь значение \"undefined\".", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "Невозможно повторно экспортировать тип, если установлен флажок \"--isolatedModules\".", "Cannot_read_file_0_Colon_1_5012": "Не удается считать файл \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Невозможно повторно объявить переменную \"{0}\" с областью видимости \"Блок\".", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "Измените \"extends\" на \"implements\".", - "Change_spelling_to_0_90022": "Изменить правописание на \"{0}\".", + "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}\".", "Circular_definition_of_import_alias_0_2303": "Циклическое определение псевдонима импорта \"{0}\".", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Обнаружена цикличность при разрешении конфигурации: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "Класс \"{0}\" определяет функцию-элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет ее как свойство-элемент экземпляра.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "Класс \"{0}\" определяет свойство-элемент экземпляра \"{1}\", а расширенный класс \"{2}\" определяет его как функцию-элемент экземпляра.", "Class_0_incorrectly_extends_base_class_1_2415": "Класс \"{0}\" неправильно расширяет базовый класс \"{1}\".", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Класс \"{0}\" неправильно реализует класс \"{1}\". Вы хотели расширить \"{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\".", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Содержащий файл не указан, корневой каталог невозможно определить. Выполняется пропуск поиска в папке node_modules.", "Convert_function_0_to_class_95002": "Преобразование функции \"{0}\" в класс", "Convert_function_to_an_ES2015_class_95001": "Преобразование функции в класс ES2015", + "Convert_to_ES6_module_95017": "Преобразовать в модуль ES6", "Convert_to_default_import_95013": "Преобразовать в импорт по умолчанию", "Corrupted_locale_file_0_6051": "Поврежденный файл языкового стандарта \"{0}\".", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Не удалось найти файл объявления модуля \"{0}\". \"{1}\" имеет неявный тип \"any\".", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Ожидалось объявление.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Имя объявления конфликтует со встроенным глобальным идентификатором \"{0}\".", "Declaration_or_statement_expected_1128": "Ожидалось объявление или оператор.", - "Declare_method_0_90023": "Объявите метод \"{0}\".", - "Declare_property_0_90016": "Объявите свойство \"{0}\".", - "Declare_static_method_0_90024": "Объявите статический метод \"{0}\".", - "Declare_static_property_0_90027": "Объявление статического свойства \"{0}\".", + "Declare_method_0_90023": "Объявите метод \"{0}\"", + "Declare_property_0_90016": "Объявите свойство \"{0}\"", + "Declare_static_method_0_90024": "Объявите статический метод \"{0}\"", + "Declare_static_property_0_90027": "Объявите статическое свойство \"{0}\"", "Decorators_are_not_valid_here_1206": "Декораторы здесь недопустимы.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Декораторы нельзя применять к множественным методам доступа get или set с совпадающим именем.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Экспорт модуля по умолчанию использует или имеет закрытое имя \"{0}\".", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Устарело.] Используйте --skipLibCheck. Пропуск проверки типов для файлов объявления библиотеки по умолчанию.", "Digit_expected_1124": "Ожидалась цифра.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "Каталога \"{0}\" не существует. Поиск в нем будет пропускаться.", - "Disable_checking_for_this_file_90018": "Отключить проверку для этого файла.", + "Disable_checking_for_this_file_90018": "Отключите проверку для этого файла", "Disable_size_limitations_on_JavaScript_projects_6162": "Отключение ограничений на размеры в проектах JavaScript.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "Отключить строгую проверку универсальных сигнатур в типах функций.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Запретить ссылки с разным регистром, указывающие на один файл.", @@ -309,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Включение строгой проверки инициализации свойств в классах.", "Enable_strict_null_checks_6113": "Включить строгие проверки NULL.", "Enable_tracing_of_the_name_resolution_process_6085": "Включить трассировку процесса разрешения имен.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Позволяет обеспечивать взаимодействие между модулями CommonJS и ES посредством создания объектов пространства имен для всех импортов. Подразумевает \"allowSyntheticDefaultImports\".", "Enables_experimental_support_for_ES7_async_functions_6068": "Включает экспериментальную поддержку для асинхронных функций ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Включает экспериментальную поддержку для декораторов ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Включает экспериментальную поддержку для создания метаданных типа для декораторов.", @@ -325,7 +335,7 @@ "Expected_0_arguments_but_got_1_or_more_2556": "Ожидалось аргументов: {0}, получено: {1} или больше.", "Expected_0_type_arguments_but_got_1_2558": "Ожидались аргументы типа {0}, получены: {1}.", "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "Ожидается аргументов типа: {0}. Укажите их с тегом \"@extends\".", - "Expected_at_least_0_arguments_but_got_1_2555": "Ожидалось аргументов не менее: {0}, получено: {1}.", + "Expected_at_least_0_arguments_but_got_1_2555": "Ожидалось аргументов не меньше: {0}, получено: {1}.", "Expected_at_least_0_arguments_but_got_1_or_more_2557": "Ожидалось аргументов не меньше: {0}, получено: {1} или больше.", "Expected_corresponding_JSX_closing_tag_for_0_17002": "Ожидался соответствующий закрывающий тег JSX для \"{0}\".", "Expected_corresponding_closing_tag_for_JSX_fragment_17015": "Ожидался соответствующий закрывающий тег фрагмента JSX.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "Файл с именем \"{0}\" отличается от уже включенного файла с именем \"{1}\" только регистром.", "File_name_0_has_a_1_extension_stripping_it_6132": "У имени файла \"{0}\" есть расширение \"{1}\"; расширение удаляется.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Спецификация файла не может содержать родительский каталог (\"..\"), который указывается после рекурсивного подстановочного знака каталога (\"**\"): \"{0}\".", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Спецификация файла не может содержать несколько рекурсивных подстановочных знаков каталога (\"**\"): \"{0}\".", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Спецификация файла не может заканчиваться рекурсивным подстановочным знаком каталога (\"**\"): \"{0}\".", "Found_package_json_at_0_6099": "Обнаружен package.json в \"{0}\".", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Объявления функций не разрешены в блоках в строгом режиме при нацеливании ES3 или ES5.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Ожидался идентификатор. \"{0}\" является зарезервированным словом в строгом режиме. Модули автоматически находятся в строгом режиме.", "Identifier_expected_1003": "Ожидался идентификатор.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Ожидался идентификатор. Значение \"__esModule\" зарезервировано как экспортируемый маркер при преобразовании модулей ECMAScript.", - "Ignore_this_error_message_90019": "Пропустить это сообщение об ошибке.", - "Implement_inherited_abstract_class_90007": "Реализуйте унаследованный абстрактный класс.", - "Implement_interface_0_90006": "Реализуйте интерфейс \"{0}\".", + "Ignore_this_error_message_90019": "Пропустите это сообщение об ошибке", + "Implement_inherited_abstract_class_90007": "Реализуйте наследуемый абстрактный класс", + "Implement_interface_0_90006": "Реализуйте интерфейс \"{0}\"", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "Предложение Implements экспортированного класса \"{0}\" имеет или использует закрытое имя \"{1}\".", - "Import_0_from_module_1_90013": "Импорт \"{0}\" из модуля \"{1}\".", + "Import_0_from_module_1_90013": "Импортируйте \"{0}\" из модуля \"{1}\"", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "Назначение импорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"import * as ns from \"mod\", \"import {a} from \"mod\", \"import d from \"mod\" или другой формат модуля.", "Import_declaration_0_is_using_private_name_1_4000": "Объявление импорта \"{0}\" использует закрытое имя \"{1}\".", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Объявление импорта конфликтует с локальным объявлением \"{0}\".", @@ -424,10 +433,10 @@ "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}\".", + "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}\", объявленный в конструкторе.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Инициализатор параметра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный после него.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Инициализатор не предоставляет значения для элемента привязки, который не имеет значения по умолчанию.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Языковой стандарт должен иметь форму <язык> или <язык>–<территория>. Например, \"{0}\" или \"{1}\".", "Longest_matching_prefix_for_0_is_1_6108": "Самый длинный соответствующий префикс для \"{0}\": \"{1}\".", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Поиск в папке node_modules; первоначальное расположение: \"{0}\".", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Сделайте вызов \"super()\" первой инструкцией в конструкторе.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Сделайте вызов \"super()\" первой инструкцией в конструкторе", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Сопоставленный объект неявно имеет тип шаблона \"любой\".", "Member_0_implicitly_has_an_1_type_7008": "Элемент \"{0}\" неявно имеет тип \"{1}\".", "Merge_conflict_marker_encountered_1185": "Встретилась отметка о конфликте слияния.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Объединенное объявление \"{0}\" не может включать объявление экспорта по умолчанию. Рекомендуется добавить вместо него отдельное объявление \"export default {0}\".", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== Имя модуля \"{0}\" было успешно разрешено в \"{1}\". ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Тип разрешения модуля не указан, используется \"{0}\".", "Module_resolution_using_rootDirs_has_failed_6111": "Произошел сбой при разрешении модуля с помощью \"rootDirs\".", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Использовать несколько последовательных числовых разделителей запрещено.", "Multiple_constructor_implementations_are_not_allowed_2392": "Не разрешается использование нескольких реализаций конструкторов.", "NEWLINE_6061": "НОВАЯ СТРОКА", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "Именованное свойство \"{0}\" содержит типы \"{1}\" и \"{2}\", которые не являются идентичными.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Выражение неабстрактного класса не реализует унаследованный абстрактный элемент \"{0}\" класса \"{1}\".", "Not_all_code_paths_return_a_value_7030": "Не все пути кода возвращают значение.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Тип числового индекса \"{0}\" нельзя назначить типу строкового индекса \"{1}\".", + "Numeric_separators_are_not_allowed_here_6188": "Числовые разделители здесь запрещены.", "Object_is_possibly_null_2531": "Возможно, объект равен null.", "Object_is_possibly_null_or_undefined_2533": "Возможно, объект равен null или undefined.", "Object_is_possibly_undefined_2532": "Возможно, объект равен undefined.", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Тип параметра открытого статического метода задания \"{0}\" из экспортированного класса имеет или использует закрытое имя \"{1}\".", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Анализ в строгом режиме и создание директивы \"use strict\" для каждого исходного файла.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "Шаблон \"{0}\" может содержать не больше одного символа \"*\".", - "Prefix_0_with_an_underscore_90025": "Добавьте к \"{0}\" префикс — символ подчеркивания.", + "Prefix_0_with_an_underscore_90025": "Добавьте к \"{0}\" префикс — символ подчеркивания", "Print_names_of_files_part_of_the_compilation_6155": "Печатать имена файлов, входящих в компиляцию.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Печатать имена создаваемых файлов, входящих в компиляцию.", "Print_the_compiler_s_version_6019": "Печать версии компилятора.", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Свойство \"{0}\" не имеет инициализатора, и ему не гарантировано присваивание в конструкторе.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа get не задана заметка с типом возвращаемого значения.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа set не задана заметка с типом параметра.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Свойство \"{0}\" в типе \"{1}\" невозможно присвоить тому же свойству в базовом типе \"{2}\".", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Свойство \"{0}\" в типе \"{1}\" не может быть присвоено типу \"{2}\".", "Property_0_is_declared_but_its_value_is_never_read_6138": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", "Property_0_is_incompatible_with_index_signature_2530": "Свойство \"{0}\" несовместимо с сигнатурой индекса.", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Вызывать ошибку в выражениях и объявлениях с подразумеваемым типом any.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.", "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", - "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\".", + "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"", + "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.", "Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Тип возвращаемого значения общего статического метода из экспортированного класса имеет или использует закрытое имя \"{0}\".", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Повторно используются разрешения модулей, унаследованные из \"{0}\", так как они не изменились со старой программы.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Повторно используется разрешение модуля \"{0}\" в файле \"{1}\" из старой программы.", - "Rewrite_as_the_indexed_access_type_0_90026": "Необходима перезапись с типом индексного доступа {0}.", + "Rewrite_as_the_indexed_access_type_0_90026": "Перезапишите как тип с индексным доступом \"{0}\"", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Корневой каталог невозможно определить, идет пропуск первичных путей поиска.", "STRATEGY_6039": "СТРАТЕГИЯ", "Scoped_package_detected_looking_in_0_6182": "Обнаружен пакет, относящийся к области; поиск в \"{0}\"", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Параметры сопоставления источников", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Специализированная сигнатура перегрузки не поддерживает назначение неспециализированной сигнатуре.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Описатель динамического импорта не может быть элементом расширения.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "Укажите целевую версию ECMAScript: \"ES3\" (по умолчанию), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\" или \"ESNEXT\".", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "Укажите целевую версию ECMAScript: \"ES3\" (по умолчанию), \"ES5\", \"ES2015\", \"ES2016\", \"ES2017\", \"ES2018\" или \"ESNEXT\".", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "Укажите вариант создания кода JSX: \"preserve\", \"react-native\" или \"react\".", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Укажите файлы библиотеки для включения в компиляцию: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Укажите вариант создания кода модуля: \"none\", \"commonjs\", \"amd\", \"system\", \"umd\", \"es2015\", или \"ESNext\".", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Укажите корневой каталог входных файлов. Используйте его для управления структурой выходных каталогов с --outDir.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "Оператор расширения в выражениях new доступен только при разработке для ECMAScript 5 и более поздних версий.", "Spread_types_may_only_be_created_from_object_types_2698": "Типы расширения можно создавать только из типов объектов.", + "Starting_compilation_in_watch_mode_6031": "Запуск компиляции в режиме наблюдения...", "Statement_expected_1129": "Ожидался оператор.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Операторы не разрешены в окружающих контекстах.", "Static_members_cannot_reference_class_type_parameters_2302": "Статические элементы не могут ссылаться на параметры типов класса.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Ожидался строковый литерал.", "String_literal_with_double_quotes_expected_1327": "Ожидается строковый литерал с двойными кавычками.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Стилизовать ошибки и сообщения с помощью цвета и контекста (экспериментальная функция).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Последовательные объявления свойств должны иметь один и тот же тип. Свойство \"{0}\" должно иметь тип \"{1}\", но имеет здесь тип \"{2}\".", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Последующие объявления переменных должны иметь тот же тип. Переменная \"{0}\" должна иметь тип \"{1}\", однако имеет тип \"{2}\".", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "Подстановка \"{0}\" для шаблона \"{1}\" содержит неправильный тип, ожидается string, получен \"{2}\".", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "Подстановка \"{0}\" в шаблоне \"{1}\" может содержать не больше одного символа \"*\".", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "{0} не является типом массива или строки или в нем нет метода [Symbol.iterator](), который возвращает итератор.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "{0} не является типом массива или в нем нет метода [Symbol.iterator](), который возвращает итератор.", "Type_0_is_not_assignable_to_type_1_2322": "Тип \"{0}\" не может быть назначен для типа \"{1}\".", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "Тип \"{0}\" невозможно присвоить типу \"{1}\". Существует два разных типа с таким именем, но они не связаны.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "Тип \"{0}\" невозможно присвоить типу \"{1}\". Существует два разных типа с таким именем, но они не связаны.", "Type_0_is_not_comparable_to_type_1_2678": "Тип \"{0}\" невозможно сравнить с типом \"{1}\".", "Type_0_is_not_generic_2315": "Тип \"{0}\" не является универсальным.", "Type_0_provides_no_match_for_the_signature_1_2658": "Тип \"{0}\" не предоставляет соответствия для сигнатуры \"{1}\".", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Незавершенный литерал шаблона.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Вызовы функций без типов не могут принимать аргументы типов.", "Unused_label_7028": "Неиспользуемая метка.", + "Use_synthetic_default_member_95016": "Используйте искусственный элемент \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Использование строки для оператора for...of поддерживается только в ECMAScript 5 и более поздних версиях.", "VERSION_6036": "ВЕРСИЯ", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Значение типа \"{0}\" не имеет общих свойств со значением типа \"{1}\". Вы хотели вызвать его?", @@ -913,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Объявления \"const\" должны быть инициализированы.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Инициализатор элементов перечисления const был вычислен в неконечное значение.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Инициализатор элементов перечисления const был вычислен в запрещенное значение NaN.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойствам или по индексу, а также в правой части объявления присваивания импорта или экспорта.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, присваивания экспорта или запроса типа.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Невозможно вызвать оператор delete с идентификатором в строгом режиме.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Объявления перечислений могут использоваться только в TS-файле.", "export_can_only_be_used_in_a_ts_file_8003": "Элемент \"export=\" может использоваться только в TS-файле.", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "Выражения утверждения типа могут использоваться только в TS-файле.", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "Объявления параметров типа могут использоваться только в TS-файле.", "types_can_only_be_used_in_a_ts_file_8010": "Типы могут использоваться только в TS-файле.", - "unique_symbol_types_are_not_allowed_here_1335": "Типы \"уникальный символ\" здесь запрещены.", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Типы \"уникальный символ\" разрешены только в переменных в операторе с переменной.", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Типы \"уникальный символ\" невозможно использовать в объявлении переменной с именем привязки.", + "unique_symbol_types_are_not_allowed_here_1335": "Типы \"unique symbol\" здесь запрещены.", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "Типы \"unique symbol\" разрешены только у переменных в операторах с переменными.", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "Типы \"unique symbol\" невозможно использовать в объявлении переменной с именем привязки.", "with_statements_are_not_allowed_in_an_async_function_block_1300": "Операторы with не разрешено использовать в блоке асинхронной функции.", "with_statements_are_not_allowed_in_strict_mode_1101": "Операторы with не разрешено использовать в строгом режиме.", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "Выражения yield не могут быть использованы в инициализаторе параметра." diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 73cae04049958..dab9dc51cb455 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -42,12 +42,13 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "Bir oluşturucu 'void' türündeki bir ek açıklamaya sahip olamaz.", "A_get_accessor_cannot_have_parameters_1054": "Bir 'get' erişimcisi parametrelere sahip olamaz.", "A_get_accessor_must_return_a_value_2378": "'get' erişimcisinin bir değer döndürmesi gerekir.", - "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Numaralandırma bildirimdeki bir üye başlatıcısı, diğer numaralandırmalarda tanımlanan üyeler dahil olmak üzere kendinden sonra bildirilen üyelere başvuramaz.", + "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Sabit listesi bildirimindeki bir üye başlatıcısı, diğer sabit listelerinde tanımlanan üyeler dahil olmak üzere kendinden sonra bildirilen üyelere başvuramaz.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Mixin sınıfının 'any[]' türünde tek bir rest parametresi içeren bir oluşturucusu olmalıdır.", "A_module_cannot_have_multiple_default_exports_2528": "Modül, birden fazla varsayılan dışarı aktarmaya sahip olamaz.", "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden farklı bir dosyada olamaz.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Bir ad alanı stili içeri aktarma işlemi çağrılamadığından veya oluşturulamadığından çalışma zamanında hataya yol açacak.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", @@ -91,11 +92,12 @@ "Accessibility_modifier_already_seen_1028": "Erişilebilirlik değiştiricisi zaten görüldü.", "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Erişimciler yalnızca ECMAScript 5 ve üzeri hedeflenirken kullanılabilir.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "İki erişimci de soyut veya soyut olmayan olmalıdır.", - "Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekleyin.", - "Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekleyin.", - "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekleyin.", - "Add_this_to_unresolved_variable_90008": "Çözümlenmemiş değişkene 'this.' ekleyin.", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "Bir tsconfig.json dosyası eklemek, hem TypeScript hem de JavaScript dosyaları içeren projeleri düzenlemenize yardımcı olur. Daha fazla bilgi edinmek için bkz. https://aka.ms/tsconfig.", + "Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekle", + "Add_async_modifier_to_containing_function_90029": "İçeren işleve zaman uyumsuz değiştirici ekle", + "Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekle", + "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", + "Add_this_to_unresolved_variable_90008": "Çözümlenmemiş değişkene 'this.' ekle", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Bir tsconfig.json dosyası eklemek, hem TypeScript hem de JavaScript dosyaları içeren projeleri düzenlemenize yardımcı olur. Daha fazla bilgi edinmek için bkz. https://aka.ms/tsconfig.", "Additional_Checks_6176": "Ek Denetimler", "Advanced_Options_6178": "Gelişmiş Seçenekler", "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", @@ -103,7 +105,7 @@ "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", "Allow_javascript_files_to_be_compiled_6102": "Javascript dosyalarının derlenmesine izin ver.", - "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' bayrağı sağlandığında çevresel const numaralandırma değerlerine izin verilmez.", + "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' bayrağı sağlandığında çevresel const sabit listesi değerlerine izin verilmez.", "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Çevresel modül bildirimi göreli modül adını belirtemez.", "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Çevresel modüller, diğer modüllerde veya ad alanlarında iç içe bulunamaz.", "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD modülü birden fazla ad atamasında sahip olamaz.", @@ -111,12 +113,12 @@ "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Erişimci, çevresel bağlamda bildirilemez.", "An_accessor_cannot_have_type_parameters_1094": "Erişimci, tür parametrelerine sahip olamaz.", "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234": "Çevresel modül bildirimine yalnızca bir dosyadaki en üst düzeyde izin verilir.", - "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Aritmetik işlenen, 'any', 'number' veya numaralandırma türünde olmalıdır.", + "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356": "Aritmetik işlenen, 'any', 'number' veya sabit listesi türünde olmalıdır.", "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705": "ES5/ES3 içindeki zaman uyumsuz bir fonksiyon veya metot, 'Promise' oluşturucusu gerektiriyor. 'Promise' oluşturucusu için bir bildiriminizin olduğundan veya `--lib` seçeneğinize 'ES2015' eklediğinizden emin olun.", "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057": "Zaman uyumsuz bir işlev veya metot, geçerli bir beklenebilir dönüş türüne sahip olmalıdır.", "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697": "Zaman uyumsuz bir işlevin veya metodun 'Promise' döndürmesi gerekir. Bir 'Promise' bildiriminiz olduğundan emin olun veya `--lib` seçeneğinize 'ES2015' ifadesini ekleyin.", "An_async_iterator_must_have_a_next_method_2519": "Zaman uyumsuz yineleyicinin bir 'next()' metodu olmalıdır.", - "An_enum_member_cannot_have_a_numeric_name_2452": "Numaralandırma üyesi, sayısal bir ada sahip olamaz.", + "An_enum_member_cannot_have_a_numeric_name_2452": "Sabit listesi üyesi, sayısal bir ada sahip olamaz.", "An_export_assignment_can_only_be_used_in_a_module_1231": "Dışarı aktarma ataması yalnızca bir modülde kullanılabilir.", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Dışarı aktarma ataması, dışarı aktarılmış diğer öğelere sahip bir modülde kullanılamaz.", "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Ad alanında dışarı aktarma ataması kullanılamaz.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Dizin imzası parametresi, bir erişilebilirlik değiştiricisine sahip olamaz.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Dizin imzası parametresi, bir başlatıcıya sahip olamaz.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Dizin imzası parametresi, bir tür ek açıklamasına sahip olmalıdır.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Dizin imzası parametre türü bir tür diğer adı olamaz. Bunun yerine '[{0}: {1}]: {2}' yazabilirsiniz.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Dizin imzası parametre türü bir birleşim türü olamaz. Bunun yerine eşlenen nesne türü kullanabilirsiniz.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Dizin imzası parametresi, 'string' veya 'number' türünde olmalıdır.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Bir arabirim, isteğe bağlı tür bağımsız değişkenleri ile yalnızca bir tanımlayıcıyı/tam adı genişletebilir.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Arabirim, yalnızca bir sınıfı veya başka bir arabirimi genişletebilir.", @@ -165,7 +169,7 @@ "Binary_digit_expected_1177": "İkili sayı bekleniyor.", "Binding_element_0_implicitly_has_an_1_type_7031": "'{0}' bağlama öğesi, örtük olarak '{1}' türü içeriyor.", "Block_scoped_variable_0_used_before_its_declaration_2448": "Blok kapsamlı değişken '{0}', bildirilmeden önce kullanıldı.", - "Call_decorator_expression_90028": "Dekoratör ifadesini çağırın.", + "Call_decorator_expression_90028": "Dekoratör ifadesini çağır", "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020": "Dönüş türü ek açıklaması bulunmayan çağrı imzası, örtük olarak 'any' dönüş türüne sahip.", "Call_target_does_not_contain_any_signatures_2346": "Çağrı hedefi imza içermiyor.", "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}' bir ad alanı değil tür olduğundan '{0}.{1}' erişimi sağlanamıyor. '{0}[\"{1}\"]' değerini belirterek '{0}' içindeki '{1}' özelliğinin türünü almak mı istediniz?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Tür bildirim dosyaları içeri aktarılamıyor. '{1}' yerine '{0}' dosyasını içeri aktarmanız önerilir.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Dış kapsamdaki '{0}' değişkeni, blok kapsamındaki '{1}' bildirimiyle aynı kapsamda başlatılamaz.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Türü bir çağrı imzasına sahip olmayan bir ifade çağrılamaz. '{0}' türünün uyumlu çağrı imzası yok.", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", @@ -210,9 +217,9 @@ "Cannot_write_file_0_because_it_would_overwrite_input_file_5055": "Giriş dosyasının üzerine yazacağı için '{0}' dosyası yazılamıyor.", "Catch_clause_variable_cannot_have_a_type_annotation_1196": "Catch yan tümcesi değişkeni bir tür ek açıklamasına sahip olamaz.", "Catch_clause_variable_cannot_have_an_initializer_1197": "Catch yan tümcesi değişkeni bir başlatıcıya sahip olamaz.", - "Change_0_to_1_90014": "'{0}' değerini '{1}' olarak değiştirin.", - "Change_extends_to_implements_90003": "'extends' ifadesini 'implements' olarak değiştirin.", - "Change_spelling_to_0_90022": "Yazımı '{0}' olarak değiştirin.", + "Change_0_to_1_90014": "'{0}' değerini '{1}' olarak değiştir", + "Change_extends_to_implements_90003": "'extends' ifadesini 'implements' olarak değiştirin", + "Change_spelling_to_0_90022": "Yazımı '{0}' olarak değiştir", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "'{0}' ön ekinin '{1}' - '{2}' için eşleşen en uzun ön ek olup olmadığı denetleniyor.", "Circular_definition_of_import_alias_0_2303": "'{0}' içeri aktarma diğer adının döngüsel tanımı.", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "Yapılandırma çözümlenirken döngüsellik algılandı: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "'{0}' sınıfı, '{1}' örnek üyesi işlevini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi özelliği olarak tanımlar.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "'{0}' sınıfı, '{1}' örnek üyesi özelliğini tanımlar; ancak genişletilmiş '{2}' sınıfı, bunu bir örnek üyesi işlevi olarak tanımlar.", "Class_0_incorrectly_extends_base_class_1_2415": "'{0}' sınıfı, '{1}' temel sınıfını yanlış genişletiyor.", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "'{0}' sınıfı hatalı olarak '{1}' sınıfını uyguluyor. '{1}' sınıfını genişletip üyelerini bir alt sınıf olarak devralmak mı istiyordunuz?", "Class_0_incorrectly_implements_interface_1_2420": "'{0}' sınıfı, '{1}' arabirimini yanlış uyguluyor.", "Class_0_used_before_its_declaration_2449": "'{0}' sınıfı, bildiriminden önce kullanıldı.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Sınıf bildirimlerinde birden fazla `@augments` veya `@extends` etiketi olamaz.", @@ -233,7 +241,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Yapılandırma dosyasının yolu veya 'tsconfig.json' dosyasını içeren klasörün yolu belirtilen projeyi derleyin.", "Compiler_option_0_expects_an_argument_6044": "'{0}' derleyici seçeneği, bağımsız değişken bekliyor.", "Compiler_option_0_requires_a_value_of_type_1_5024": "'{0}' derleyici seçeneği, {1} türünde bir değer gerektiriyor.", - "Computed_property_names_are_not_allowed_in_enums_1164": "Numaralandırmalarda hesaplanan özellik adına izin verilmiyor.", + "Computed_property_names_are_not_allowed_in_enums_1164": "Sabit listelerinde hesaplanan özellik adına izin verilmiyor.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Dize değeri içeren üyelerin bulunduğu bir sabit listesinde hesaplanan değerlere izin verilmez.", "Concatenate_and_emit_output_to_single_file_6001": "Çıktıyı tek dosyaya birleştirin ve yayın.", "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "'{1}' ve '{2}' içinde '{0}' için çakışan tanımlar bulundu. Çakışmayı çözmek için bu kitaplığın belirli bir versiyonunu yüklemeniz önerilir.", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Kapsayıcı dosya belirtilmedi ve kök dizini belirlenemiyor; 'node_modules' klasöründe arama atlanıyor.", "Convert_function_0_to_class_95002": "'{0}' işlevini sınıfa dönüştür", "Convert_function_to_an_ES2015_class_95001": "İşlevi bir ES2015 sınıfına dönüştür", + "Convert_to_ES6_module_95017": "ES6 modülüne dönüştür", "Convert_to_default_import_95013": "Varsayılan içeri aktarmaya dönüştür", "Corrupted_locale_file_0_6051": "{0} yerel ayar dosyası bozuk.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "'{0}' modülü için bildirim dosyası bulunamadı. '{1}' örtülü olarak 'any' türüne sahip.", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "Bildirim bekleniyor.", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "Bildirim adı, yerleşik genel tanımlayıcı '{0}' ile çakışıyor.", "Declaration_or_statement_expected_1128": "Bildirim veya deyim bekleniyor.", - "Declare_method_0_90023": "'{0}' metodunu bildirin.", - "Declare_property_0_90016": "'{0}' özelliğini bildirin.", - "Declare_static_method_0_90024": "'{0}' statik metodunu bildirin.", - "Declare_static_property_0_90027": "'{0}' statik özelliğini bildirin.", + "Declare_method_0_90023": "'{0}' metodunu bildir", + "Declare_property_0_90016": "'{0}' özelliğini bildir", + "Declare_static_method_0_90024": "'{0}' statik metodunu bildir", + "Declare_static_property_0_90027": "'{0}' statik özelliğini bildir", "Decorators_are_not_valid_here_1206": "Buradaki dekoratörler geçerli değil.", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekoratörler aynı ada sahip birden fazla get/set erişimcisine uygulanamaz.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Modülün varsayılan dışarı aktarımı '{0}' özel adına sahip veya bu adı kullanıyor.", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Kullanım Dışı] Bunun yerine '--skipLibCheck' kullanın. Varsayılan kitaplık bildirim dosyalarının tür denetimini atlayın.", "Digit_expected_1124": "Rakam bekleniyor.", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "'{0}' dizini yok, içindeki tüm aramalar atlanıyor.", - "Disable_checking_for_this_file_90018": "Bu dosya için denetimi devre dışı bırakın.", + "Disable_checking_for_this_file_90018": "Bu dosya için denetimi devre dışı bırak", "Disable_size_limitations_on_JavaScript_projects_6162": "JavaScript projelerinde boyut sınırlamalarını devre dışı bırakın.", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "İşlev türlerinde genel imzalar için katı denetimi devre dışı bırakın.", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "Aynı dosyaya yönelik tutarsız büyük/küçük harflere sahip başvurulara izin verme.", @@ -275,7 +284,7 @@ "Do_not_emit_outputs_6010": "Çıktıları gösterme.", "Do_not_emit_outputs_if_any_errors_were_reported_6008": "Herhangi bir hata bildirildiyse çıkışları gösterme.", "Do_not_emit_use_strict_directives_in_module_output_6112": "Modül çıkışında 'use strict' yönergeleri gösterme.", - "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Oluşturulan kodda const numaralandırma bildirimlerini silme.", + "Do_not_erase_const_enum_declarations_in_generated_code_6007": "Oluşturulan kodda const sabit listesi bildirimlerini silme.", "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "Derlenen çıkışta '__extends' gibi özel yardımcı işlevler oluşturmayın.", "Do_not_include_the_default_library_file_lib_d_ts_6158": "Varsayılan kitaplık dosyasını (lib.d.ts) eklemeyin.", "Do_not_report_errors_on_unreachable_code_6077": "Erişilemeyen kod ile ilgili hataları bildirme.", @@ -309,22 +318,23 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Tüm içeri aktarma işlemleri için ad alanı nesnelerinin oluşturulması aracılığıyla CommonJS ile ES Modülleri arasında yayımlama birlikte çalışabilirliğine imkan tanır. Şu anlama gelir: 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", "Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.", - "Enum_declarations_must_all_be_const_or_non_const_2473": "Numaralandırma bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", - "Enum_member_expected_1132": "Numaralandırma üyesi bekleniyor.", - "Enum_member_must_have_initializer_1061": "Numaralandırma üyesi bir başlatıcıya sahip olmalıdır.", + "Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", + "Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.", + "Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.", "Enum_name_cannot_be_0_2431": "Sabit listesi adı '{0}' olamaz.", "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535": "Sabit listesi türü '{0}', sabit değer olmayan başlatıcılara sahip üyeler içeriyor.", "Examples_Colon_0_6026": "Örnekler: {0}", "Excessive_stack_depth_comparing_types_0_and_1_2321": "Aşırı yığın derinliği, '{0}' ve '{1}' türlerini karşılaştırıyor.", - "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} türünde bağımsız değişkenler bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", + "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027": "{0}-{1} tür bağımsız değişkeni bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", "Expected_0_arguments_but_got_1_2554": "{0} bağımsız değişken bekleniyordu ancak {1} alındı.", "Expected_0_arguments_but_got_1_or_more_2556": "{0} bağımsız değişken bekleniyordu ancak {1} veya daha fazla bağımsız değişken alındı.", - "Expected_0_type_arguments_but_got_1_2558": "{0} türünde bağımsız değişkenler bekleniyordu ancak {1} alındı.", - "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} türünde bağımsız değişkenler bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", + "Expected_0_type_arguments_but_got_1_2558": "{0} tür bağımsız değişkeni bekleniyordu ancak {1} alındı.", + "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026": "{0} tür bağımsız değişkeni bekleniyordu; bunları bir '@extends' etiketiyle sağlayın.", "Expected_at_least_0_arguments_but_got_1_2555": "En az {0} bağımsız değişken bekleniyordu ancak {1} alındı.", "Expected_at_least_0_arguments_but_got_1_or_more_2557": "En az {0} bağımsız değişken bekleniyordu ancak {1} veya daha fazla bağımsız değişken alındı.", "Expected_corresponding_JSX_closing_tag_for_0_17002": "'{0}' için ilgili JSX kapanış etiketi bekleniyor.", @@ -340,8 +350,8 @@ "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Dışarı aktarılan dış paket yazı dosyası '{0}', bir modül değil. Paket tanımını güncelleştirmek için lütfen paket yazarı ile iletişime geçin.", "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654": "Dışarı aktarılan dış paket yazıları, üç eğik çizgili başvurular içeremez. Paket tanımını güncelleştirmek için lütfen paket yazarı ile iletişime geçin.", "Exported_type_alias_0_has_or_is_using_private_name_1_4081": "Dışarı aktarılan '{0}' tür diğer adı, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Dışarı aktarılan '{0}' değişkeni, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", - "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Dışarı aktarılan '{0}' değişkeni, '{2}' özel modüldeki '{1}' özel adına sahip veya bu adı kullanıyor.", + "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "Dışarı aktarılan '{0}' değişkeni, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "Dışarı aktarılan '{0}' değişkeni, '{2}' özel modüldeki '{1}' adına sahip veya bu adı kullanıyor.", "Exported_variable_0_has_or_is_using_private_name_1_4025": "Dışarı aktarılan '{0}' değişkeni, '{1}' özel adına sahip veya bu adı kullanıyor.", "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "Modül genişletmelerinde dışarı aktarmalara ve dışarı aktarma atamalarına izin verilmez.", "Expression_expected_1109": "İfade bekleniyor.", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "'{0}' dosya adının, zaten eklenmiş olan '{1}' dosya adından tek farkı, büyük/küçük harf kullanımı.", "File_name_0_has_a_1_extension_stripping_it_6132": "'{0}' dosya adında '{1}' uzantısı var; uzantı ayrılıyor.", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "Dosya belirtimi, özyinelemeli dizin joker karakterinden ('**') sonra görünen bir üst dizin ('..') içeremez: '{0}'.", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "Dosya belirtimi, birden fazla özyinelemeli dizin joker karakter ('**') içeremez: '{0}'.", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "Dosya belirtimi, özyinelemeli dizin joker karakter ('**') ile bitemez: '{0}'.", "Found_package_json_at_0_6099": "'{0}' içinde 'package.json' bulundu.", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "Katı modda 'ES3' veya 'ES5' hedeflenirken blokların içinde işlev bildirimlerine izin verilmez.", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "Tanımlayıcı bekleniyor. '{0}', katı modda ayrılmış bir sözcüktür. Modüller otomatik olarak katı moddadır.", "Identifier_expected_1003": "Tanımlayıcı bekleniyor.", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "Tanımlayıcı bekleniyor. '__esModule', ECMAScript modülleri dönüştürülürken, dışarı aktarılan bir işaretçi olarak ayrılmış.", - "Ignore_this_error_message_90019": "Bu hata iletisini yoksayın.", - "Implement_inherited_abstract_class_90007": "Devralınmış soyut sınıfı uygulayın.", - "Implement_interface_0_90006": "'{0}' arabirimini uygulayın.", + "Ignore_this_error_message_90019": "Bu hata iletisini yoksay", + "Implement_inherited_abstract_class_90007": "Devralınan soyut sınıfı uygula", + "Implement_interface_0_90006": "'{0}' arabirimini uygula", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "'{1}' özel adına sahip veya bu adı kullanan '{0}' dışarı aktarılan sınıfının yan tümcesini uygular.", - "Import_0_from_module_1_90013": "\"{1}\" modülünden '{0}' öğesini içeri aktarın.", + "Import_0_from_module_1_90013": "\"{1}\" modülünden '{0}' öğesini içeri aktar", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript modülleri hedeflenirken içeri aktarma ataması kullanılamaz. Bunun yerine 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"' veya başka bir modül biçimi kullanmayı deneyin.", "Import_declaration_0_is_using_private_name_1_4000": "'{0}' içeri aktarma bildirimi, '{1}' özel adına sahip veya bu adı kullanıyor.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "İçeri aktarma bildirimi, yerel '{0}' bildirimiyle çakışıyor.", @@ -417,17 +426,17 @@ "Import_name_cannot_be_0_2438": "İçeri aktarma adı '{0}' olamaz.", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "Çevresel modül bildirimindeki içeri veya dışarı aktarma bildirimi, göreli modül adı aracılığıyla modüle başvuramaz.", "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667": "Modül genişletmelerinde içeri aktarmalara izin verilmez. Bunları, kapsayan dış modüle taşımanız önerilir.", - "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Çevresel numaralandırma bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", - "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Birden fazla bildirime sahip numaralandırmada yalnızca bir bildirim ilk numaralandırma öğesine ait başlatıcıyı atlayabilir.", - "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' numaralandırma bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", + "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "Çevresel sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", + "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "Birden fazla bildirime sahip sabit listesinde yalnızca bir bildirim ilk sabit listesi öğesine ait başlatıcıyı atlayabilir.", + "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "'const' sabit listesi bildirimlerinde, üye başlatıcısı sabit ifade olmalıdır.", "Index_signature_in_type_0_only_permits_reading_2542": "'{0}' türündeki dizin imzası yalnızca okumaya izin veriyor.", "Index_signature_is_missing_in_type_0_2329": "'{0}' türündeki dizin imzası yok.", "Index_signatures_are_incompatible_2330": "Dizin imzaları uyumsuz.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "'{0}' birleştirilmiş bildirimindeki bildirimlerin tümü dışarı aktarılmış veya yerel olmalıdır.", - "Infer_parameter_types_from_usage_95012": "Parametre türlerini kullanımdan çıkarsayın.", - "Infer_type_of_0_from_usage_95011": "'{0}' türünü kullanımdan çıkarsayın.", - "Initialize_property_0_in_the_constructor_90020": "Oluşturucu içinde '{0}' özelliğini başlatın.", - "Initialize_static_property_0_90021": "'{0}' statik özelliğini başlatın.", + "Infer_parameter_types_from_usage_95012": "Parametre türleri için kullanımdan çıkarım yap", + "Infer_type_of_0_from_usage_95011": "'{0}' türü için kullanımdan çıkarım yap", + "Initialize_property_0_in_the_constructor_90020": "Oluşturucu içinde '{0}' özelliğini başlat", + "Initialize_static_property_0_90021": "'{0}' statik özelliğini başlat", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "'{0}' örnek üyesi değişkeninin başlatıcısı, oluşturucuda bildirilen '{1}' tanımlayıcısına başvuramaz.", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "'{0}' parametresinin başlatıcısı, kendinden sonra bildirilen '{1}' tanımlayıcısına başvuramaz.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Başlatıcı bu bağlama öğesi için bir değer sağlamıyor ve bağlama öğesi varsayılan değere sahip değil.", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "Yerel ayar, veya - biçiminde olmalıdır. Örneğin, '{0}' veya '{1}'.", "Longest_matching_prefix_for_0_is_1_6108": "'{0}' için eşleşen en uzun ön ek: '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' klasöründe aranıyor; ilk konum: '{0}'.", - "Make_super_call_the_first_statement_in_the_constructor_90002": "Oluşturucudaki ilk deyime 'super()' tarafından çağrı yapılmasını sağla.", + "Make_super_call_the_first_statement_in_the_constructor_90002": "Oluşturucudaki ilk deyime 'super()' tarafından çağrı yapılmasını sağla", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Eşleştirilmiş nesne türü örtük olarak 'any' şablon türüne sahip.", "Member_0_implicitly_has_an_1_type_7008": "'{0}' üyesi örtük olarak '{1}' türüne sahip.", "Merge_conflict_marker_encountered_1185": "Birleştirme çakışması işaretçisiyle karşılaşıldı.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "'{0}' birleştirilen bildirimi, varsayılan bir dışarı aktarma bildirimini içeremez. Bunun yerine ayrı bir 'export default {0}' bildirimi eklemeyi göz önünde bulundurun.", @@ -502,12 +512,13 @@ "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145": "'{1}' dosyası değiştirilmediğinden '{0}' modülü, bu dosyada bildirilen çevresel modül olarak çözümlendi.", "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144": "'{0}' modülü, '{1}' dosyasında yerel olarak bildirilmiş çevresel modül olarak çözümlendi.", "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142": "'{0}' modülü '{1}' olarak çözüldü ancak '--jsx' ayarlanmadı.", - "Module_Resolution_Options_6174": "Modül Çözünürlüğü Seçenekleri", + "Module_Resolution_Options_6174": "Modül Çözümleme Seçenekleri", "Module_name_0_matched_pattern_1_6092": "Modül adı: '{0}', eşleşen desen: '{1}'.", "Module_name_0_was_not_resolved_6090": "======== '{0}' modül adı çözümlenemedi. ========", "Module_name_0_was_successfully_resolved_to_1_6089": "======== '{0}' modül adı '{1}' öğesine başarıyla çözümlendi. ========", "Module_resolution_kind_is_not_specified_using_0_6088": "Modül çözümleme türü belirtilmedi, '{0}' kullanılıyor.", "Module_resolution_using_rootDirs_has_failed_6111": "'rootDirs' kullanarak modül çözümleme başarısız oldu.", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "Birbirini izleyen birden çok sayısal ayırıcıya izin verilmez.", "Multiple_constructor_implementations_are_not_allowed_2392": "Birden çok oluşturucu uygulamasına izin verilmez.", "NEWLINE_6061": "YENİ SATIR", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "'{1}' ve '{2}' türündeki '{0}' adlı özellikler aynı değil.", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Soyut olmayan sınıf ifadesi, '{1}' sınıfından devralınan '{0}' soyut üyesini uygulamıyor.", "Not_all_code_paths_return_a_value_7030": "Tüm kod yolları bir değer döndürmez.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "'{0}' sayısal dizin türü, '{1}' dize dizini türüne atanamaz.", + "Numeric_separators_are_not_allowed_here_6188": "Burada sayısal ayırıcılara izin verilmez.", "Object_is_possibly_null_2531": "Nesne büyük olasılıkla 'null'.", "Object_is_possibly_null_or_undefined_2533": "Nesne büyük olasılıkla 'null' veya 'undefined'.", "Object_is_possibly_undefined_2532": "Nesne büyük olasılıkla 'undefined'.", @@ -558,44 +570,45 @@ "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' parametresi, '{1}' parametresi ile aynı konumda değil.", "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063": "Dışarı aktarılan sınıftaki oluşturucunun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065": "Dışarı aktarılan arabirimdeki oluşturucu imzasının '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Dışarı aktarılan işlevin '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076": "Dışarı aktarılan işlevin '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077": "Dışarı aktarılan işlevin '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078": "Dışarı aktarılan işlevin '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091": "Dışarı aktarılan arabirimin dizin imzasındaki '{0}' parametresi, '{2}' adlı özel modüldeki '{1}' adına sahip ya da bu adı kullanıyor.", "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092": "Dışarı aktarılan arabirimin dizin imzasındaki '{0}' parametresi, '{1}' adına sahip ya da bu adı kullanıyor.", "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074": "Dışarı aktarılan arabirimdeki metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075": "Dışarı aktarılan arabirimdeki metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068": "Dışarı aktarılan sınıftaki ortak metodun '{0}' parametresi, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069": "Dışarı aktarılan sınıftaki statik metodun '{0}' parametresi, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070": "Dışarı aktarılan sınıftaki statik metodun '{0}' parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", "Parameter_cannot_have_question_mark_and_initializer_1015": "Parametre soru işareti ve başlatıcı içeremez.", "Parameter_declaration_expected_1138": "Parametre bildirimi bekleniyor.", - "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", - "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{1}' özel adını taşıyor veya kullanıyor.", - "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", - "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{1}' özel adını taşıyor veya kullanıyor.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037": "Dışarı aktarılan sınıftaki genel ayarlayıcı '{0}' için parametre türü, '{1}' özel adına sahip veya bu adı kullanıyor.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "Dışarı aktarılan sınıftaki genel statik ayarlayıcı '{0}' için parametre türü, '{1}' özel adına sahip veya bu adı kullanıyor.", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "Katı modda ayrıştırın ve her kaynak dosya için \"use strict\" kullanın.", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "'{0}' deseni en fazla bir adet '*' karakteri içerebilir.", - "Prefix_0_with_an_underscore_90025": "'{0}' için ön ek olarak alt çizgi kullanın.", + "Prefix_0_with_an_underscore_90025": "'{0}' için ön ek olarak alt çizgi kullan", "Print_names_of_files_part_of_the_compilation_6155": "Derlemenin parçası olan dosyaların adlarını yazdırın.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Oluşturulan dosyalardan, derlemenin parçası olanların adlarını yazdırın.", "Print_the_compiler_s_version_6019": "Derleyici sürümünü yazdır.", "Print_this_message_6017": "Bu iletiyi yazdır.", - "Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' numaralandırması üzerinde değil.", + "Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' sabit listesi üzerinde değil.", "Property_0_does_not_exist_on_type_1_2339": "'{0}' özelliği, '{1}' türünde değil.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' özelliği '{1}' türünde yok. Bunu mu demek istediniz: '{2}'?", "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "'{0}' özelliği, çakışan bildirimler içeriyor ve '{1}' türü içinde erişilebilir değil.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "'{0}' özelliği başlatıcı içermiyor ve oluşturucuda kesin olarak atanmamış.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' özelliği, get erişimcisinin dönüş türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' özelliği, set erişimcisinin parametre türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' türündeki '{0}' özelliği, '{2}' temel türündeki aynı özelliğe atanamaz.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' türündeki '{0}' özelliği, '{2}' türüne atanamaz.", "Property_0_is_declared_but_its_value_is_never_read_6138": "'{0}' özelliği bildirildi ancak değeri hiç okunmadı.", "Property_0_is_incompatible_with_index_signature_2530": "'{0}' özelliği, dizin imzasıyla uyumsuz.", @@ -622,19 +635,20 @@ "Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098": "Dışarı aktarılan sınıfın '{0}' genel metodu, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099": "Dışarı aktarılan sınıfın '{0}' genel metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100": "Dışarı aktarılan sınıfın '{0}' genel metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031": "Dışarı aktarılan sınıfın '{0}' ortak özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097": "Dışarı aktarılan sınıfın '{0}' genel statik metodu, '{1}' özel adına sahip veya bu adı kullanıyor.", - "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, {2} dış modülündeki '{1}' özel adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", + "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, {2} dış modülündeki '{1}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028": "Dışarı aktarılan sınıfın '{0}' ortak statik özelliği, '{1}' özel adına sahip veya bu adı kullanıyor.", "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "Belirtilen 'any' türüne sahip ifade ve bildirimlerde hata oluştur.", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Örtük olarak 'any' türü içeren 'this' ifadelerinde hata tetikle.", "Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.", - "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldırın.", + "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", + "Replace_import_with_0_95015": "İçeri aktarma işlemini '{0}' ile değiştirin.", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "İşlevdeki tüm kod yolları bir değer döndürmediğinde hata bildir.", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "switch deyiminde sonraki ifadelere geçiş ile ilgili hataları bildir.", "Report_errors_in_js_files_8019": ".js dosyalarındaki hataları bildirin.", @@ -666,21 +680,21 @@ "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049": "Dışarı aktarılan arabirimdeki dizin imzasının dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056": "Dışarı aktarılan arabirimdeki metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057": "Dışarı aktarılan arabirimdeki metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adını taşıyor veya kullanıyor ancak adlandırılamıyor.", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", - "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{1}' özel adını taşıyor veya kullanıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adına sahip veya bu adı kullanıyor ancak adlandırılamıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043": "Dışarı aktarılan sınıftaki genel alıcı '{0}' için dönüş türü, '{1}' özel adına sahip veya bu adı kullanıyor.", "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055": "Dışarı aktarılan sınıftaki ortak metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adını taşıyor veya kullanıyor ancak adlandırılamıyor.", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adını taşıyor veya kullanıyor.", - "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{1}' özel adını taşıyor veya kullanıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' dış modülündeki '{1}' adına sahip veya bu adı kullanıyor ancak adlandırılamıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{2}' özel modülündeki '{1}' adına sahip veya bu adı kullanıyor.", + "Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040": "Dışarı aktarılan sınıftaki genel statik alıcı '{0}' için dönüş türü, '{1}' özel adına sahip veya bu adı kullanıyor.", "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{1}' dış modülündeki '{0}' adına sahip veya bu adı kullanıyor, ancak adlandırılamıyor.", "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{1}' özel modülündeki '{0}' adına sahip veya bu adı kullanıyor.", "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "Dışarı aktarılan sınıftaki ortak statik metodun dönüş türü, '{0}' özel adına sahip veya bu adı kullanıyor.", - "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Eski programdaki çözmeler değişmediğinden '{0}' kaynaklı modül çözmeleri yeniden kullanılıyor.", + "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "Eski programdaki çözümlemeler değişmediğinden '{0}' kaynaklı modül çözümlemeleri yeniden kullanılıyor.", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "Eski programın '{1}' dosyasında '{0}' modülü çözmesi yeniden kullanılıyor.", - "Rewrite_as_the_indexed_access_type_0_90026": "Dizine eklenmiş erişim türü '{0}' olarak yeniden yazın.", + "Rewrite_as_the_indexed_access_type_0_90026": "Dizine eklenmiş erişim türü '{0}' olarak yeniden yaz", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "Kök dizin belirlenemiyor, birincil arama yolları atlanıyor.", "STRATEGY_6039": "STRATEJİ", "Scoped_package_detected_looking_in_0_6182": "Kapsamlı paket algılandı, '{0}' içinde aranıyor", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "Kaynak Eşleme Seçenekleri", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "Özelleşmiş aşırı yükleme imzası özelleşmemiş imzalara atanamaz.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "Dinamik içeri aktarmanın tanımlayıcısı, yayılma öğesi olamaz.", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "ECMAScript hedef sürümünü belirleyin: 'ES3' (varsayılan), 'ES5', 'ES2015', 'ES2016', 'ES2017' ya da 'ESNEXT'.", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "ECMAScript hedef sürümünü belirleyin: 'ES3' (varsayılan), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018' ya da 'ESNEXT'.", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "JSX kod oluşturma seçeneğini belirtin: 'preserve', 'react-native' veya 'react'.", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "Derlemeye dahil edilecek kitaplık dosyalarını belirtin: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "Modül kodu oluşturmayı belirtin: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' veya 'ESNext'.", @@ -704,7 +718,8 @@ "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "Hata ayıklayıcının, eşlem dosyalarını üretilen konumlar yerine nerede bulması gerektiğini belirtin.", "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "Giriş dosyalarının kök dizinini belirtin. Çıkış dizininin yapısını --outDir ile denetlemek için kullanın.", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "'new' ifadelerindeki yayılma işleci yalnızca ECMAScript 5 ve üzeri hedeflenirken kullanılabilir.", - "Spread_types_may_only_be_created_from_object_types_2698": "Spread türleri yalnızca nesne türlerinden oluşturulabilir.", + "Spread_types_may_only_be_created_from_object_types_2698": "Yayılma türleri yalnızca nesne türlerinden oluşturulabilir.", + "Starting_compilation_in_watch_mode_6031": "Derleme, izleme modunda başlatılıyor...", "Statement_expected_1129": "Deyim bekleniyor.", "Statements_are_not_allowed_in_ambient_contexts_1036": "Çevresel bağlamlarda deyimlere izin verilmez.", "Static_members_cannot_reference_class_type_parameters_2302": "Statik üyeler sınıf türündeki parametrelere başvuramaz.", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "Dize sabit değeri bekleniyor.", "String_literal_with_double_quotes_expected_1327": "Çift tırnak içine alınmış bir dize sabit değeri bekleniyor.", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "Renk ve bağlam kullanarak hataların ve iletilerin stilini belirleyin (deneysel).", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Ardışık özellik bildirimleri aynı türe sahip olmalıdır. '{0}' özelliği '{1}' türünde olmalıdır, ancak burada '{2}' türüne sahip.", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "Ardışık değişken bildirimleri aynı türe sahip olmalıdır. '{0}' değişkeni '{1}' türünde olmalıdır, ancak burada '{2}' türüne sahip.", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "'{1}' deseni için '{0}' alternatifinin türü hatalı; beklenen: 'string' alınan: '{2}'.", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "'{1}' desenindeki '{0}' değişimi, en fazla bir adet '*' karakteri içerebilir.", @@ -745,7 +760,7 @@ "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405": "'for...in' deyiminin sol tarafı 'string' veya 'any' türünde olmalıdır.", "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483": "'for...of' deyiminin sol tarafında tür ek açıklaması kullanılamaz.", "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487": "'for...of' deyiminin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", - "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Aritmetik işlemin sol tarafı, 'any', 'number' veya bir numaralandırma türünde olmalıdır.", + "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362": "Aritmetik işlemin sol tarafı, 'any', 'number' veya bir sabit listesi türünde olmalıdır.", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Atama ifadesinin sol tarafında bir değişken veya özellik erişimi bulunmalıdır.", "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360": "'in' ifadesinin sol tarafı, 'any', 'string', 'number' veya 'symbol' türünde olmalıdır.", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "'instanceof' ifadesinin sol tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", @@ -760,7 +775,7 @@ "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Zaman uyumsuz bir işlevin dönüş türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Zaman uyumsuz bir işlevin ya da metodun döndürme türü, genel Promise türü olmalıdır.", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407": "'for...in' deyiminin sağ tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", - "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Aritmetik işlemin sağ tarafı, 'any', 'number' veya bir numaralandırma türünde olmalıdır.", + "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363": "Aritmetik işlemin sağ tarafı, 'any', 'number' veya bir sabit listesi türünde olmalıdır.", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' ifadesinin sağ tarafı 'any' türünde, bir nesne türü veya tür parametresi olmalıdır.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "'instanceof' ifadesinin sağ tarafı 'any' türünde veya 'Function' arabirim türüne atanabilir bir türde olmalıdır.", "The_specified_path_does_not_exist_Colon_0_5058": "Belirtilen yol yok: '{0}'.", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "'{0}' türü, bir dizi türü veya dize türü değil ya da bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip değil.", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "'{0}' türü, bir dizi türü değil ya da bir yineleyici döndüren '[Symbol.iterator]()' metoduna sahip değil.", "Type_0_is_not_assignable_to_type_1_2322": "'{0}' türü, '{1}' türüne atanamaz.", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "'{0}' türü '{1}' türüne atanamaz. Bu ada sahip iki farklı tür mevcut, ancak bu türler birbiriyle ilişkisiz.", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "'{0}' türü '{1}' türüne atanamaz. Bu ada sahip iki farklı tür mevcut, ancak bu türler birbiriyle ilişkisiz.", "Type_0_is_not_comparable_to_type_1_2678": "'{0}' türü '{1}' türüyle karşılaştırılamaz.", "Type_0_is_not_generic_2315": "'{0}' türü genel değil.", "Type_0_provides_no_match_for_the_signature_1_2658": "'{0}' türü, '{1}' imzası için eşleşme sağlamıyor.", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "Sonlandırılmamış şablon sabit değeri.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Türü belirtilmemiş işlev çağrıları tür bağımsız değişkenlerini kabul etmeyebilir.", "Unused_label_7028": "Kullanılmayan etiket.", + "Use_synthetic_default_member_95016": "Yapay 'default' üyesini kullanın.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' deyiminde dize kullanma yalnızca ECMAScript 5 veya üzerinde desteklenir.", "VERSION_6036": "SÜRÜM", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' türünün değeri ile '{1}' türü arasında hiç ortak özellik yok. Bunun yerine çağrı yapmak mı istediniz?", @@ -911,9 +927,9 @@ "class_expressions_are_not_currently_supported_9003": "'class' ifadeleri şu anda desteklenmiyor.", "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' bildirimleri yalnızca bir bloğun içinde bildirilebilir.", "const_declarations_must_be_initialized_1155": "'const' bildirimlerinin başlatılması gerekiyor.", - "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' numaralandırma üyesi başlatıcısı, sonlu olmayan bir değer olarak hesaplandı.", - "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' numaralandırma üyesi başlatıcısı, izin verilmeyen 'NaN' değeri olarak hesaplandı.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' numaralandırmaları yalnızca bir özellikte, dizin erişim ifadelerinde, içeri aktarma bildiriminin sağ tarafında veya dışarı aktarma atamasında kullanılabilir.", + "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' sabit listesi üyesi başlatıcısı, sonlu olmayan bir değer olarak hesaplandı.", + "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' sabit listesi üyesi başlatıcısı, izin verilmeyen 'NaN' değeri olarak hesaplandı.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' sabit listeleri yalnızca bir özellikte, dizin erişim ifadelerinde, içeri aktarma bildiriminin veya dışarı aktarma atamasının sağ tarafında ya da tür sorgusunda kullanılabilir.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete', katı moddaki bir tanımlayıcıda çağrılamaz.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' yalnızca bir .ts dosyasında kullanılabilir.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' yalnızca bir .ts dosyasında kullanılabilir.", @@ -921,7 +937,7 @@ "extends_clause_already_seen_1172": "'extends' yan tümcesi zaten görüldü.", "extends_clause_must_precede_implements_clause_1173": "'extends' yan tümcesi, 'implements' yan tümcesinden önce gelmelidir.", "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "Dışarı aktarılan '{0}' sınıfının 'extends' yan tümcesi, '{1}' özel adına sahip veya bu adı kullanıyor.", - "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Dışarı aktarılan '{0}' arabirimin 'extends' yan tümcesi, '{1}' özel adına sahip veya bu adı kullanıyor.", + "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022": "Dışarı aktarılan '{0}' arabiriminin 'extends' yan tümcesi, '{1}' özel adına sahip veya bu adı kullanıyor.", "file_6025": "dosya", "get_and_set_accessor_must_have_the_same_this_type_2682": "'get' ve 'set' erişimcisi aynı 'this' türüne sahip olmalıdır.", "get_and_set_accessor_must_have_the_same_type_2380": "'get' ve 'set' erişimcisi aynı türde olmalıdır.", diff --git a/lib/tsc.js b/lib/tsc.js index 6efd1a954836b..3c7996f362555 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -36,24 +36,6 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); - var NodeBuilderFlags; - (function (NodeBuilderFlags) { - NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; - NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -150,7 +132,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -159,6 +141,7 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -284,6 +267,9 @@ var ts; } ts.forEach = forEach; function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -293,6 +279,19 @@ var ts; return undefined; } ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -309,13 +308,27 @@ var ts; ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { var result = []; - Debug.assert(arrayA.length === arrayB.length); + Debug.assertEqual(arrayA.length, arrayB.length); for (var i = 0; i < arrayA.length; i++) { result.push(callback(arrayA[i], arrayB[i], i)); } return result; } ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; function zipToMap(keys, values) { Debug.assert(keys.length === values.length); var map = createMap(); @@ -388,17 +401,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -470,11 +472,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -535,25 +538,33 @@ var ts; return result; } ts.flatMap = flatMap; - function flatMapIter(iter, mapfn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapfn(value); - if (res) { - if (isArray(res)) { - result.push.apply(result, res); - } - else { - result.push(res); + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); } - } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; } - return result; } - ts.flatMapIter = flatMapIter; + ts.flatMapIterator = flatMapIterator; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -576,12 +587,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -590,20 +612,35 @@ var ts; return result; } ts.mapDefined = mapDefined; - function mapDefinedIter(iter, mapFn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapFn(value); - if (res !== undefined) { - result.push(res); + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } } - } - return result; + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; } - ts.mapDefinedIter = mapDefinedIter; + ts.singleIterator = singleIterator; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1243,6 +1280,8 @@ var ts; ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; function notImplemented() { throw new Error("Not implemented"); } @@ -1570,7 +1609,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47) + if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) return 3; } if (path.lastIndexOf("file:///", 0) === 0) { @@ -1637,10 +1676,6 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function moduleHasNonRelativeName(moduleName) { - return !ts.isExternalModuleNameRelative(moduleName); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -1663,7 +1698,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -1946,7 +1983,6 @@ var ts; function getSubPatternFromSpec(spec, basePath, usage, _a) { var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; - var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); var lastComponent = lastOrUndefined(components); @@ -1961,11 +1997,7 @@ var ts; for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { var component = components_1[_i]; if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - return undefined; - } subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; } else { if (usage === "directories") { @@ -2233,10 +2265,10 @@ var ts; } function Signature() { } function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0; this.modifierFlagsCache = 0; this.transformFlags = 0; @@ -2363,9 +2395,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; function matchPatternOrExact(patternStrings, candidate) { @@ -2462,170 +2492,20 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - clearCache(); - } - else { - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - clearCache(); - } - else { - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.singleElementArray = singleElementArray; })(ts || (ts = {})); var ts; (function (ts) { @@ -2862,7 +2742,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -2890,6 +2770,9 @@ var ts; return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } var nodeSystem = { + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -2968,7 +2851,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -3294,6 +3182,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3408,6 +3298,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -3462,7 +3353,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -3550,6 +3441,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3628,6 +3520,10 @@ var ts; Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3714,7 +3610,6 @@ var ts; The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), @@ -3765,6 +3660,7 @@ var ts; Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), @@ -3805,7 +3701,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -3912,6 +3808,9 @@ var ts; Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -3940,6 +3839,9 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -4015,9 +3917,9 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -4029,6 +3931,9 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); var ts; @@ -4436,7 +4341,7 @@ var ts; } function scanConflictMarkerTrivia(text, pos, error) { if (error) { - error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); } var ch = text.charCodeAt(pos); var len = text.length; @@ -4660,19 +4565,60 @@ var ts; lookAhead: lookAhead, scanRange: scanRange, }; - function error(message, length) { + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } if (onError) { + var oldPos = pos; + pos = errPos; onError(message, length || 0); + pos = oldPos; + } + } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); } function scanNumber() { var start = pos; - while (isDigit(text.charCodeAt(pos))) - pos++; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; if (text.charCodeAt(pos) === 46) { pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; + decimalFragment = scanNumberFragment(); } var end = pos; if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { @@ -4680,17 +4626,29 @@ var ts; tokenFlags |= 16; if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++; - if (isDigit(text.charCodeAt(pos))) { - pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; - end = pos; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); } else { - error(ts.Diagnostics.Digit_expected); + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + if (tokenFlags & 512) { + var result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; } + return "" + +result; + } + else { + return "" + +(text.substring(start, end)); } - return "" + +(text.substring(start, end)); } function scanOctalDigits() { var start = pos; @@ -4699,17 +4657,35 @@ var ts; } return +(text.substring(start, pos)); } - function scanExactNumberOfHexDigits(count) { - return scanHexDigits(count, false); + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(count, false, canHaveSeparators); } - function scanMinimumNumberOfHexDigits(count) { - return scanHexDigits(count, true); + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(count, true, canHaveSeparators); } - function scanHexDigits(minCount, scanAsManyAsPossible) { + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { var digits = 0; var value = 0; + var allowSeparator = false; + var isPreviousTokenSeparator = false; while (digits < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; if (ch >= 48 && ch <= 57) { value = value * 16 + ch - 48; } @@ -4724,10 +4700,14 @@ var ts; } pos++; digits++; + isPreviousTokenSeparator = false; } if (digits < minCount) { value = -1; } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return value; } function scanString(jsxAttributeString) { @@ -4863,7 +4843,7 @@ var ts; } } function scanHexadecimalEscape(numDigits) { - var escapedValue = scanExactNumberOfHexDigits(numDigits); + var escapedValue = scanExactNumberOfHexDigits(numDigits, false); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); } @@ -4873,7 +4853,7 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1); + var escapedValue = scanMinimumNumberOfHexDigits(1, false); var isInvalidExtendedEscape = false; if (escapedValue < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); @@ -4912,7 +4892,7 @@ var ts; if (pos + 5 < end && text.charCodeAt(pos + 1) === 117) { var start_1 = pos; pos += 2; - var value = scanExactNumberOfHexDigits(4); + var value = scanExactNumberOfHexDigits(4, false); pos = start_1; return value; } @@ -4960,8 +4940,26 @@ var ts; ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; + var separatorAllowed = false; + var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; var valueOfCh = ch - 48; if (!isDigit(ch) || valueOfCh >= base) { break; @@ -4969,10 +4967,15 @@ var ts; value = value * base + valueOfCh; pos++; numberOfDigits++; + isPreviousTokenSeparator = false; } if (numberOfDigits === 0) { return -1; } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + return value; + } return value; } function scan() { @@ -5158,7 +5161,7 @@ var ts; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1); + var value = scanMinimumNumberOfHexDigits(1, true); if (value < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -5479,7 +5482,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -5501,6 +5504,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9: case 11: @@ -5511,55 +5515,30 @@ var ts; } return token = 5; case 64: - pos++; return token = 57; case 10: case 13: - pos++; return token = 4; case 42: - pos++; return token = 39; case 123: - pos++; return token = 17; case 125: - pos++; return token = 18; case 91: - pos++; return token = 21; case 93: - pos++; return token = 22; case 60: - pos++; return token = 27; - case 62: - pos++; - return token = 29; case 61: - pos++; return token = 58; case 44: - pos++; return token = 26; case 46: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24; - } return token = 23; - case 33: - pos++; - return token = 51; - case 63: - pos++; - return token = 55; } if (isIdentifierStart(ch, 6)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } @@ -5567,7 +5546,7 @@ var ts; return token = 71; } else { - return pos += 1, token = 0; + return token = 0; } } function speculationHelper(callback, isLookahead) { @@ -5644,8 +5623,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.emptyArray = []; + ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -5665,15 +5645,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return str += " "; }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -5685,10 +5674,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -5722,12 +5711,19 @@ var ts; return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -5898,7 +5894,7 @@ var ts; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { - if (!nodeIsSynthesized(node) && node.parent) { + if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; @@ -6296,7 +6292,7 @@ var ts; return node === parent.type; case 182: case 183: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184: return false; } @@ -6972,41 +6968,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 && node.body && node.body.kind === 234 && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -7030,7 +7015,7 @@ var ts; if (node.kind === 147) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -7129,6 +7114,29 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208: + case 209: + case 221: + case 212: + case 222: + case 236: + case 261: + case 262: + case 223: + case 215: + case 216: + case 217: + case 213: + case 214: + case 225: + case 264: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -7441,6 +7449,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; function isESSymbolIdentifier(node) { return node.kind === 71 && node.escapedText === "Symbol"; } @@ -7852,7 +7864,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -8028,7 +8052,7 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (node.type) { + if (ts.hasType(node)) { return node.type; } if (checkJSDoc || isInJavaScriptFile(node)) { @@ -8402,14 +8426,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -8705,6 +8729,10 @@ var ts; return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9378,7 +9406,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192; + return node.kind === 190; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -9822,7 +9850,7 @@ var ts; } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { - return ts.isIdentifier(node) && node.autoGenerateKind > 0; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; } ts.isGeneratedIdentifier = isGeneratedIdentifier; function isModifierKind(token) { @@ -9929,6 +9957,17 @@ var ts; return node && (node.kind === 154 || node.kind === 155); } ts.isAccessor = isAccessor; + function isMethodOrAccessor(node) { + switch (node.kind) { + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; function isTypeElement(node) { var kind = node.kind; return kind === 157 @@ -10410,6 +10449,33 @@ var ts; return !!node.jsDoc && node.jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257: + case 259: + case 265: + case 266: + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); var ts; (function (ts) { @@ -10472,20 +10538,48 @@ var ts; case 267: return visitNode(cbNode, node.expression); case 147: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 150: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 149: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 265: - case 227: - case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 227: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); + case 177: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 161: case 162: case 156: @@ -11001,15 +11095,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -11445,9 +11531,12 @@ var ts; return token() === 26 || token() === 24 || isIdentifierOrPattern(); case 18: return isIdentifier(); - case 11: case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); + if (token() === 26) { + return true; + } + case 11: + return token() === 24 || isStartOfExpression(); case 16: return isStartOfParameter(); case 19: @@ -11607,6 +11696,9 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -11907,7 +11999,7 @@ var ts; node.isUnterminated = true; } if (node.kind === 8) { - node.numericLiteralFlags = scanner.getTokenFlags() & 496; + node.numericLiteralFlags = scanner.getTokenFlags() & 1008; } nextToken(); finishNode(node); @@ -12850,7 +12942,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -14289,6 +14383,7 @@ var ts; switch (token()) { case 19: case 27: + case 51: case 56: case 58: case 55: @@ -14845,7 +14940,6 @@ var ts; return result; } scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; var state = 1; var margin = undefined; var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; @@ -14856,23 +14950,22 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5) { + t = nextJSDocToken(); } - if (token() === 4) { + if (t === 4) { state = 0; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1) { - switch (token()) { + loop: while (true) { + switch (t) { case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); parseTag(indent); state = 0; - advanceToken = false; margin = undefined; indent++; } @@ -14911,18 +15004,13 @@ var ts; indent += whitespace.length; break; case 1: - break; + break loop; default: state = 2; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -15006,7 +15094,8 @@ var ts; if (!tag) { return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -15019,8 +15108,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 && token() !== 1) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4: if (state >= 1) { state = 0; @@ -15029,7 +15119,9 @@ var ts; indent = 0; break; case 57: - break; + scanner.setTextPos(scanner.getTextPos() - 1); + case 1: + break loop; case 5: if (state === 2) { pushComment(scanner.getTokenText()); @@ -15045,7 +15137,7 @@ var ts; case 39: if (state === 0) { state = 1; - indent += scanner.getTokenText().length; + indent += 1; break; } default: @@ -15053,14 +15145,11 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57) { - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281, atToken.pos); @@ -15068,8 +15157,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -15138,10 +15226,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280, start_2); @@ -15245,10 +15330,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -15293,8 +15375,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57: if (canParseTag) { var child = tryParseChildTag(target); @@ -15334,33 +15415,43 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0; + break; case "arg": case "argument": case "param": - return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -15379,6 +15470,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -15911,7 +16010,7 @@ var ts; case 147: ts.Debug.assert(node.parent.kind === 277); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -16245,7 +16344,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 || expr2.kind === 13); + } + function isNarrowableInOperands(left, right) { + return (left.kind === 9 || left.kind === 13) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -16259,6 +16361,8 @@ var ts; isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 93: return isNarrowableOperand(expr.left); + case 92: + return isNarrowableInOperands(expr.left, expr.right); case 26: return isNarrowingExpression(expr.right); } @@ -17456,23 +17560,9 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { setCommonJsModuleIndicator(node); return; } @@ -17526,7 +17616,7 @@ var ts; if (node.kind === 195) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { bindExportsPropertyAssignment(node); } else { @@ -17535,11 +17625,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -17630,7 +17716,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1, 107455); @@ -17707,6 +17793,28 @@ var ts; return true; } } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { @@ -17761,6 +17869,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180: return computePropertyAccess(node, subtreeFlags); + case 181: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -17769,13 +17879,15 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3; } if (subtreeFlags & 524288 - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 | 268435456))) { transformFlags |= 192; + if (expression.transformFlags & 268435456) { + transformFlags |= 16384; + } } if (expression.kind === 91) { transformFlags |= 67108864; @@ -17784,19 +17896,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97: - return true; - case 180: - case 181: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97; - } - return false; + return transformFlags & ~940049729; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17807,7 +17907,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; + return transformFlags & ~940049729; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17824,7 +17924,7 @@ var ts; transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17847,7 +17947,7 @@ var ts; transformFlags |= 192 | 131072; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17880,7 +17980,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -17892,7 +17992,7 @@ var ts; transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17908,7 +18008,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17919,7 +18019,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; + return transformFlags & ~940574017; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -17927,7 +18027,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17939,7 +18039,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -17961,7 +18061,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -17976,7 +18076,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; @@ -17984,7 +18084,7 @@ var ts; transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -18014,7 +18114,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18036,7 +18136,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -18055,17 +18155,27 @@ var ts; transformFlags |= 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; + return transformFlags & ~1003902273; } function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (transformFlags & 134217728) { + transformFlags ^= 134217728; + transformFlags |= 268435456; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~671089985; + } + function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; + var expressionFlags = expression.transformFlags; + if (expressionFlags & 134217728) { + transformFlags &= ~134217728; + transformFlags |= 268435456; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~671089985; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18077,7 +18187,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -18092,7 +18202,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18101,7 +18211,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18109,7 +18219,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18117,7 +18227,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -18126,7 +18236,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; + return transformFlags & ~977327425; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432; @@ -18137,16 +18247,22 @@ var ts; transformFlags |= 192 | 4194304; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; + return transformFlags & ~948962625; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 536872257; + var excludeFlags = 939525441; switch (kind) { case 120: case 192: transformFlags |= 8 | 16; break; + case 185: + case 203: + case 292: + transformFlags |= 3; + excludeFlags = 536872257; + break; case 114: case 112: case 113: @@ -18155,8 +18271,6 @@ var ts; case 76: case 233: case 268: - case 185: - case 203: case 204: case 131: transformFlags |= 3; @@ -18254,7 +18368,8 @@ var ts; transformFlags |= 8 | 1048576; break; case 97: - transformFlags |= 192; + transformFlags |= 192 | 134217728; + excludeFlags = 536872257; break; case 99: transformFlags |= 16384; @@ -18264,11 +18379,11 @@ var ts; if (subtreeFlags & 524288) { transformFlags |= 8 | 1048576; } - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 176: transformFlags |= 192 | 8388608; - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 177: transformFlags |= 192; @@ -18280,7 +18395,7 @@ var ts; transformFlags |= 3 | 4096; break; case 179: - excludeFlags = 540087617; + excludeFlags = 942740801; if (subtreeFlags & 2097152) { transformFlags |= 192; } @@ -18293,7 +18408,7 @@ var ts; break; case 178: case 183: - excludeFlags = 537396545; + excludeFlags = 940049729; if (subtreeFlags & 524288) { transformFlags |= 192; } @@ -18328,27 +18443,27 @@ var ts; case 182: case 183: case 178: - return 537396545; + return 940049729; case 234: - return 574674241; + return 977327425; case 147: - return 536872257; + return 939525441; case 188: - return 601249089; + return 1003902273; case 187: case 229: - return 601281857; + return 1003935041; case 228: - return 546309441; + return 948962625; case 230: case 200: - return 539358529; + return 942011713; case 153: - return 601015617; + return 1003668801; case 152: case 154: case 155: - return 601015617; + return 1003668801; case 119: case 133: case 130: @@ -18367,14 +18482,23 @@ var ts; case 232: return -3; case 179: - return 540087617; + return 942740801; case 264: - return 537920833; + return 940574017; case 175: case 176: - return 537396545; - default: + return 940049729; + case 185: + case 203: + case 292: + case 186: + case 97: return 536872257; + case 180: + case 181: + return 671089985; + default: + return 939525441; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -18385,7 +18509,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -18478,8 +18602,9 @@ var ts; visitType(type.modifiersType); } function visitSignature(signature) { - if (signature.typePredicate) { - visitType(signature.typePredicate.type); + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); } ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { @@ -18572,9 +18697,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -19007,8 +19132,8 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { @@ -19025,10 +19150,16 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - if (!compilerOptions.preserveSymlinks) { - resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + var originalPath = void 0; + if (!compilerOptions.preserveSymlinks && resolvedValue) { + originalPath = resolvedValue.path; + var path = realPath(resolved_1.value.path, host, traceEnabled); + if (path === originalPath) { + originalPath = undefined; + } + resolvedValue = __assign({}, resolvedValue, { path: path }); } - return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -19063,7 +19194,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -19077,6 +19210,38 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts"; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } @@ -19150,18 +19315,41 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { - var host = _a.host, traceEnabled = _a.traceEnabled; + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); + if (subModuleName === "") { + var path = tryReadPackageJsonFields(true, packageJsonContent, nodeModuleDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + } + else { + var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); + if (typeof jsPath === "string") { + subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js"), ".jsx") + ".d.ts"; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts")) { + subModuleName = addExtensionAndIndex(subModuleName); + } var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -19304,13 +19492,17 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -19326,7 +19518,7 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, undefined, false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { @@ -19364,7 +19556,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, undefined, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; function toSearchResult(value) { @@ -19469,6 +19661,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -19502,16 +19699,32 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { node = ts.getParseTreeNode(node, ts.isExpression); return node ? getContextualType(node) : undefined; }, + isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { node = ts.getParseTreeNode(node, ts.isCallLikeExpression); @@ -19526,7 +19739,11 @@ var ts; }, isValidPropertyAccess: function (node, propertyName) { node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (node, type, property) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); }, getSignatureFromDeclaration: function (declaration) { declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); @@ -19550,7 +19767,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -19590,11 +19807,17 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -19638,6 +19861,7 @@ var ts; var markerSubType = createType(32768); markerSubType.constraint = markerSuperType; var markerOtherType = createType(32768); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); @@ -19645,6 +19869,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); + var reverseMappedCache = ts.createMap(); var ambientModulesCache; var patternAmbientModules; var globalObjectType; @@ -19739,12 +19964,144 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - var _displayBuilder; var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 | 8192, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 | 3112960 | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -19760,8 +20117,10 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { - getDiagnostics(sourceFile, cancellationToken); + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -19996,7 +20355,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { if (declaration.kind === 177) { @@ -20060,10 +20419,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; var result; var lastLocation; @@ -20217,7 +20577,7 @@ var ts; } break; } - if (location.kind !== 208) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; @@ -20233,7 +20593,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -20281,6 +20643,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208: + case 235: + case 222: + case 236: + case 261: + case 262: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -20436,6 +20812,30 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export="); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + if (!file || file.isDeclarationFile) { + if (resolveExportByName(moduleSymbol, "default", dontResolveAlias)) { + return false; + } + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + return false; + } + return true; + } + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -20444,15 +20844,14 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -20730,7 +21129,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -20758,8 +21157,41 @@ var ts; } function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 | 3))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -20981,11 +21413,11 @@ var ts; } var visitedSymbolTables = []; return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols); + var result = trySymbolTable(symbols, ignoreQualification); visitedSymbolTables.pop(); return result; } @@ -20993,16 +21425,16 @@ var ts; return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function isUMDExportSymbol(symbol) { return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.escapedName))) { + function trySymbolTable(symbols, ignoreQualification) { + if (isAccessible(symbols.get(symbol.escapedName), undefined, ignoreQualification)) { return [symbol]; } return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { @@ -21011,10 +21443,11 @@ var ts; && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, true); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -21063,6 +21496,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); return access.accessibility === 0; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455, false); + return access.accessibility === 0; + } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; @@ -21153,97 +21590,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4; } + var nodeFlags = 3112960; + if (flags & 2) { + nodeFlags |= 128; + } + if (flags & 1) { + nodeFlags |= 512; + } + var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, entity, sourceFile, writer); + return writer; + } } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144) { + sigOutput = kind === 1 ? 162 : 161; + } + else { + sigOutput = kind === 1 ? 157 : 156; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, sig, sourceFile, writer); + return writer; + } } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608; + context.flags &= ~8388608; if (!type) { context.encounteredError = true; return undefined; @@ -21280,6 +21751,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024) { + if (!(context.flags & 1048576)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140, ts.createKeywordTypeNode(137)); } if (type.flags & 2048) { @@ -21301,10 +21777,13 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 32768 && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304) { + if (!context.encounteredError && !(context.flags & 32768)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -21317,7 +21796,7 @@ var ts; var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } - if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -21330,7 +21809,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144)) { context.encounteredError = true; } return undefined; @@ -21355,7 +21834,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1); @@ -21363,7 +21842,7 @@ var ts; function createAnonymousTypeNode(type) { var symbol = type.symbol; if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455); @@ -21382,10 +21861,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; + if (isConstructorObject) { + return createTypeNodeFromObjectType(type); + } + else { + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } } } else { @@ -21400,7 +21885,8 @@ var ts; return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); + return (!!(context.flags & 4096) || ts.contains(context.symbolStack, symbol)) && + (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } } @@ -21425,11 +21911,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, false); @@ -21442,7 +21928,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -21456,12 +21942,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -21537,7 +22028,10 @@ var ts; typeElements.push(signatureToSignatureDeclarationHelper(signature, 157, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); + var indexInfo = resolvedType.objectFlags & 2048 ? + createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : + resolvedType.stringIndexInfo; + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); @@ -21548,9 +22042,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); + if (context.flags & 2048) { + if (propertySymbol.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 | 16) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455); + } + } var propertyName = symbolToName(propertySymbol, context, 107455, true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; @@ -21591,19 +22100,29 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152)) { + context.encounteredError = true; + } return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); } var returnTypeNode; - if (signature.typePredicate) { - var typePredicate = signature.typePredicate; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { var parameterName = typePredicate.kind === 1 ? ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : ts.createThisTypeNode(); @@ -21614,7 +22133,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256) { if (returnTypeNode && returnTypeNode.kind === 119) { returnTypeNode = undefined; } @@ -21622,14 +22141,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var savedContextFlags = context.flags; + context.flags &= ~512; var name = symbolToName(type.symbol, context, 793064, true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -21640,7 +22162,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -21664,45 +22186,20 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -21725,11 +22222,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, predicate, sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -21785,6 +22364,9 @@ var ts; return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 && symbol.escapedName === "default") { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -21794,7 +22376,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072)) { context.encounteredError = true; } switch (declaration.kind) { @@ -21813,668 +22395,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91) { - writePunctuation(writer, 21); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91) { - writePunctuation(writer, 22); - } - } - else { - writePunctuation(writer, 23); - writer.writeSymbol(symbolName, symbol); - } - } - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 256 & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 | 16384); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024; - if (type.flags & 33585807) { - writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 && !(type.flags & 131072)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 || type.flags & (272 | 32768)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 1024) && type.aliasSymbol && - ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 | 32)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024) { - if (flags & 131072) { - writeKeyword(writer, 140); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137); - } - else if (type.flags & 96) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128); - if (flags & 128) { - writePunctuation(writer, 20); - } - } - else if (type.flags & 1048576) { - writeType(type.objectType, 128); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 17); - writeSpace(writer); - writePunctuation(writer, 24); - writeSpace(writer); - writePunctuation(writer, 18); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 ? 0 : 128); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); - } - if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 512); - pos++; - while (pos < end) { - writePunctuation(writer, 26); - writeSpace(writer); - writeType(typeArguments[pos], 0); - pos++; - } - writePunctuation(writer, 29); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 128 | 32768); - writePunctuation(writer, 21); - writePunctuation(writer, 22); - } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); - } - else if (flags & 16384 && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200) { - writeAnonymousType(type, flags); - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128) { - writePunctuation(writer, 19); - } - if (type.flags & 131072) { - writeTypeList(formatUnionTypes(type.types), 49); - } - else { - writeTypeList(type.types, 48); - } - if (flags & 128) { - writePunctuation(writer, 20); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - if (symbol.flags & 32 && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 && flags & 16384) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); - } - else { - writeKeyword(writer, 119); - } - } - else { - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192) && - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 || declaration.parent.kind === 235; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 4) || - ts.contains(symbolStack, symbol); - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 103); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - if (typeFormatFlags & 32768) { - writePunctuation(writer, 20); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216) { - writePunctuation(writer, 55); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128) { - return true; - } - else if (flags & 512) { - var typeParameters = callSignature.target && (flags & 64) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 94); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (flags & 128) { - writePunctuation(writer, 20); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384) { - if (p.flags & 4194304) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56); - writeSpace(writer); - writeType(t, globalFlags & 16384); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); - if (type.declaration.questionToken) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 175) { - writePunctuation(writer, 17); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); - } - else if (bindingPattern.kind === 176) { - writePunctuation(writer, 21); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); - } - writePunctuation(writer, 22); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 512; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - flags = 0; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99); - } - writeSpace(writer); - writeKeyword(writer, 126); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 && isTypeAny(returnType)) { - return; - } - if (flags & 16) { - writeSpace(writer); - writePunctuation(writer, 36); - } - else { - writePunctuation(writer, 56); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); - writeSpace(writer); - } - if (signature.target && (flags & 64)) { - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); - writeSpace(writer); - switch (kind) { - case 1: - writeKeyword(writer, 133); - break; - case 0: - writeKeyword(writer, 136); - break; - } - writePunctuation(writer, 22); - writePunctuation(writer, 56); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -22586,8 +22506,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -22621,6 +22541,10 @@ var ts; if (propertyName === 3) { return target.resolvedReturnType; } + if (propertyName === 4) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } function popTypeResolution() { @@ -22726,7 +22650,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); @@ -22742,7 +22667,7 @@ var ts; type = createArrayType(elementType); } else { - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -22761,7 +22686,7 @@ var ts; type = getTypeWithFacts(type, 131072); } return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + getUnionType([type, checkExpressionCached(declaration.initializer)], 2) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -22784,21 +22709,21 @@ var ts; return strictNullChecks && optional ? getOptionalType(type) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.parent.parent.kind === 216) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 216) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); return indexType.flags & (32768 | 524288) ? indexType : stringType; } - if (declaration.parent.parent.kind === 217) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 217) { var forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; } if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, !!declaration.questionToken && includeOptionality); + var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && declaration.kind === 227 && !ts.isBindingPattern(declaration.name) && @@ -22832,19 +22757,16 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } } if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } if (ts.isJsxAttribute(declaration)) { return trueType; } - if (declaration.kind === 266) { - return checkIdentifier(declaration.name); - } if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, false, true); } @@ -22887,7 +22809,7 @@ var ts; types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } } - var type = jsDocType || getUnionType(types, true); + var type = jsDocType || getUnionType(types, 2); return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { @@ -22957,15 +22879,12 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (type.flags & 1024 && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 1024 && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } - if (declaration.kind === 265) { - return type; - } return getWidenedType(type); } - type = declaration.dotDotDotToken ? anyArrayType : anyType; + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && noImplicitAny) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { reportImplicitAnyError(declaration, type); @@ -22978,6 +22897,12 @@ var ts; var memberDeclaration = root.kind === 147 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { @@ -23002,9 +22927,38 @@ var ts; declaration.kind === 180 && declaration.parent.kind === 195) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else { + else if (ts.isJSDocPropertyTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } + else { + ts.Debug.fail("Unhandled declaration kind! " + ts.SyntaxKind[declaration.kind]); + } if (!popTypeResolution()) { type = reportCircularityError(symbol); } @@ -23161,6 +23115,9 @@ var ts; if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } + if (ts.getCheckFlags(symbol) & 2048) { + return getTypeOfReverseMappedSymbol(symbol); + } if (symbol.flags & (3 | 4)) { return getTypeOfVariableOrParameterOrProperty(symbol); } @@ -23352,10 +23309,10 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = ts.emptyArray; + type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (65536 | 262144 | 1))) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); @@ -23372,22 +23329,25 @@ var ts; var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; + return type.resolvedBaseTypes = ts.emptyArray; } baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === unknownType) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - return; + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + type.members = undefined; } - type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; @@ -23421,7 +23381,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); } } else { @@ -23569,7 +23529,7 @@ var ts; } } if (memberTypeList.length) { - var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + var enumType_1 = getUnionType(memberTypeList, 1, symbol, undefined); if (enumType_1.flags & 131072) { enumType_1.flags |= 256; enumType_1.symbol = symbol; @@ -23657,7 +23617,7 @@ var ts; } function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isThislessType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); } function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); @@ -23825,18 +23785,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -23866,6 +23827,7 @@ var ts; if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); var thisArgument = ts.lastOrUndefined(typeArguments); for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { var baseType = baseTypes_1[_i]; @@ -23893,21 +23855,21 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; + sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -23924,7 +23886,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -23974,12 +23936,13 @@ var ts; if (unionSignatures) { var s = signature; if (unionSignatures.length > 1) { - s = cloneSignature(signature); + var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); } - s.resolvedReturnType = undefined; + s = cloneSignature(signature); + s.thisParameter = thisParameter; s.unionSignatures = unionSignatures; } (result || (result = [])).push(s); @@ -24001,7 +23964,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, 2), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -24084,6 +24047,7 @@ var ts; if (symbol.exports) { members = getExportsOfSymbol(symbol); } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -24110,6 +24074,23 @@ var ts; } } } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0); + var readonlyMask = type.mappedType.declaration.readonlyToken ? false : true; + var optionalMask = type.mappedType.declaration.questionToken ? 0 : 16777216; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 | (readonlyMask && isReadonlySymbol(prop) ? 8 : 0); + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); var stringIndexInfo; @@ -24218,6 +24199,9 @@ var ts; else if (type.objectFlags & 3) { resolveClassOrInterfaceMembers(type); } + else if (type.objectFlags & 2048) { + resolveReverseMappedTypeMembers(type); + } else if (type.objectFlags & 16) { resolveAnonymousTypeMembers(type); } @@ -24303,12 +24287,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0)) { + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -24327,29 +24314,30 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216) { var types = t.types; @@ -24369,7 +24357,7 @@ var ts; return stringType; } if (t.flags & 1048576) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -24385,7 +24373,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -24429,14 +24417,13 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; - var types = containingType.types; var isUnion = containingType.flags & 131072; var excludeModifiers = isUnion ? 24 : 0; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var current = types_5[_i]; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -24467,8 +24454,8 @@ var ts; var propTypes = []; var declarations = []; var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -24559,7 +24546,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, true); + return getUnionType(propTypes, 2); } } return undefined; @@ -24614,7 +24601,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -24622,27 +24609,26 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 71) { - return { - kind: 1, - parameterName: parameterName ? parameterName.escapedText : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; + return createIdentifierTypePredicate(parameterName && parameterName.escapedText, parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); } else { - return { - kind: 0, - type: getTypeFromTypeNode(node.type) - }; + return createThisTypePredicate(type); } } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0, type: type }; + } function getMinTypeArgumentCount(typeParameters) { var minTypeArgumentCount = 0; if (typeParameters) { @@ -24728,18 +24714,15 @@ var ts; : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 159 ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } function maybeAddJsSyntheticRestParameter(declaration, parameters) { var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -24848,6 +24831,28 @@ var ts; return getTypeOfSymbol(signature.thisParameter); } } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var declaration = signature.declaration; + signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 159 ? + createTypePredicateFromTypePredicateNode(declaration.type) : + noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3)) { @@ -24858,7 +24863,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2); } else { type = getReturnTypeFromBody(signature.declaration); @@ -24994,12 +24999,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -25016,8 +25021,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -25064,7 +25069,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, undefined, 1); + var typeStr = typeToString(type, undefined, 2); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { return unknownType; @@ -25460,14 +25465,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -25525,7 +25530,8 @@ var ts; } } } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1; } if (types.length === 0) { return neverType; } @@ -25537,11 +25543,15 @@ var ts; if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsLiteralOrUniqueESSymbol) { - removeRedundantLiteralTypes(typeSet); + switch (unionReduction) { + case 1: + if (typeSet.containsLiteralOrUniqueESSymbol) { + removeRedundantLiteralTypes(typeSet); + } + break; + case 2: + removeSubtypes(typeSet); + break; } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : @@ -25550,6 +25560,38 @@ var ts; } return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; @@ -25572,7 +25614,7 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } @@ -25603,8 +25645,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } @@ -25629,7 +25671,7 @@ var ts; var unionIndex = typeSet.unionIndex; if (unionIndex !== undefined) { var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), 1, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); @@ -25658,7 +25700,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -25707,6 +25749,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -25778,33 +25821,51 @@ var ts; } return false; } - function getTransformedIndexedAccessType(type) { + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 && getTemplateTypeFromMappedType(type) === neverType; + } + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - if (objectType.flags & 262144 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); + if (objectType.flags & 262144 && isGenericObjectType(objectType)) { + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + if (ts.some(objectType.types, isMappedTypeToNever)) { + var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); + return getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { @@ -25893,10 +25954,7 @@ var ts; if (right.flags & 131072) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 33554432) { - return nonPrimitiveType; - } - if (right.flags & (136 | 84 | 524322 | 272)) { + if (right.flags & (136 | 84 | 524322 | 272 | 33554432)) { return left; } var members = ts.createSymbolTable(); @@ -25947,8 +26005,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= propagatedFlags; - spread.flags |= 2097152 | 8388608; + spread.flags |= propagatedFlags | 8388608; spread.objectFlags |= (128 | 1024); return spread; } @@ -26158,7 +26215,7 @@ var ts; return createTypeMapper(sources, undefined); } function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -26180,7 +26237,7 @@ var ts; result.target = typeParameter; return result; } - function cloneTypePredicate(predicate, mapper) { + function instantiateTypePredicate(predicate, mapper) { if (ts.isIdentifierTypePredicate(predicate)) { return { kind: 1, @@ -26198,7 +26255,6 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); @@ -26207,10 +26263,7 @@ var ts; tp.mapper = mapper; } } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -26335,7 +26388,7 @@ var ts; } } if (type.flags & 131072 && !(type.flags & 16382)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return getUnionType(instantiateTypes(type.types, mapper), 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (type.flags & 262144) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); @@ -26494,7 +26547,7 @@ var ts; var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288) === (getFalsyFlags(targetType) & 12288); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : @@ -26513,11 +26566,13 @@ var ts; return result; } var sourceReturnType = getReturnTypeOfSignature(source); - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); } @@ -26625,7 +26680,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 64)); } enumRelation.set(id, false); return false; @@ -26707,6 +26762,9 @@ var ts; } return false; } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return source.flags & 67108864 && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var maybeKeys; @@ -26724,10 +26782,22 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, undefined); + if (helpfulRetry) { + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -26737,8 +26807,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 256); - targetType = typeToString(target, undefined, 256); + sourceType = typeToString(source, undefined, 64); + targetType = typeToString(target, undefined, 64); } if (!message) { if (relation === comparableRelation) { @@ -27192,8 +27262,11 @@ var ts; return result; } } - else if (target.flags & 1048576 && source.indexType === target.indexType) { + else if (target.flags & 1048576) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -27298,6 +27371,9 @@ var ts; if (!(targetProp.flags & 4194304)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { @@ -27479,6 +27555,9 @@ var ts; var result = -1; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, undefined)) { + continue; + } if (kind === 0 || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -27619,7 +27698,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -27773,17 +27852,24 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } return result; } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 : compareTypes(source.type, target.type); + } function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -27806,7 +27892,7 @@ var ts; var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288); }); return primaryTypes.length ? getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288) : - getUnionType(types, true); + getUnionType(types, 2); } function getCommonSubtype(types) { return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); @@ -27865,8 +27951,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -28035,7 +28121,7 @@ var ts; if (type.flags & 131072) { var unionContext_1 = context || createWideningContext(undefined, undefined, type.types); var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 ? t : getWidenedTypeWithContext(t, unionContext_1); }); - return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 : 1); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -28111,6 +28197,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -28165,6 +28254,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -28175,6 +28265,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -28206,7 +28297,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -28216,40 +28307,43 @@ var ts; var indexInfo = type.flags & 2 ? createIndexInfo(emptyObjectType, false) : undefined; return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } - function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { + function inferTypeForHomomorphicMappedType(source, target) { + var key = source.id + "," + target.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target) { var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0); - if (properties.length === 0 && !indexInfo) { + if (properties.length === 0 && !getIndexInfoOfType(source, 0)) { return undefined; } - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var inference = createInferenceInfo(typeParameter); - var inferences = [inference]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 16777216; - var members = ts.createSymbolTable(); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var propType = getTypeOfSymbol(prop); - if (propType.flags & 16777216) { + if (getTypeOfSymbol(prop).flags & 16777216) { return undefined; } - var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); - inferredProp.declarations = prop.declarations; - inferredProp.type = inferTargetType(propType); - members.set(prop.escapedName, inferredProp); - } - if (indexInfo) { - indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); - return inference.candidates ? getUnionType(inference.candidates, true) : emptyObjectType; } + var reversed = createObjectType(2048 | 16, undefined); + reversed.source = source; + reversed.mappedType = target; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + } + function inferReverseMappedType(sourceType, target) { + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return inference.candidates ? getUnionType(inference.candidates, 2) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -28264,10 +28358,11 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { + function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -28316,22 +28411,27 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - var p = priority | (source === implicitNeverType ? 16 : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { + if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -28346,15 +28446,15 @@ var ts; } } else if (source.flags & 524288 && target.flags & 524288) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1; + contravariant = !contravariant; } else if (source.flags & 1048576 && target.flags & 1048576) { inferFromTypes(source.objectType, target.objectType); @@ -28376,7 +28476,7 @@ var ts; } if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2; + priority |= 1; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -28415,9 +28515,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -28444,16 +28544,10 @@ var ts; if (constraintType.flags & 524288) { var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); - if (ts.contains(mappedTypeStack, key)) { - return; - } - (mappedTypeStack || (mappedTypeStack = [])).push(key); - var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); - mappedTypeStack.pop(); + var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4; + priority |= 2; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -28495,8 +28589,10 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromContravariantTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); @@ -28523,8 +28619,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -28552,7 +28648,7 @@ var ts; if (candidates.length > 1) { var objectLiterals = ts.filter(candidates, isObjectLiteralType); if (objectLiterals.length) { - var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, true)); + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2)); return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); } } @@ -28569,10 +28665,16 @@ var ts; !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = inference.priority & 1 ? getCommonSubtype(baseCandidates) : - context.flags & 1 || inference.priority & 8 ? getUnionType(baseCandidates, true) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 || inference.priority & 4 ? + getUnionType(baseCandidates, 2) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + if (inferredType.flags & 16384 && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2) { inferredType = silentNeverType; @@ -28612,7 +28714,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -28790,8 +28892,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -28855,14 +28957,6 @@ var ts; return 8388607; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576) { - 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) { @@ -28899,7 +28993,7 @@ var ts; parent.parent.kind === 217 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -28938,7 +29032,7 @@ var ts; var type = pattern.kind === 175 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -29049,15 +29143,15 @@ var ts; } return f(type) ? type : neverType; } - function mapType(type, mapper) { + function mapType(type, mapper, noReductions) { if (!(type.flags & 131072)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -29071,7 +29165,7 @@ var ts; } } } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 : 1) : mappedType; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -29112,7 +29206,7 @@ var ts; return elementType.flags & 16384 ? autoArrayType : createArrayType(elementType.flags & 131072 ? - getUnionType(elementType.types, true) : + getUnionType(elementType.types, 2) : elementType); } function getFinalArrayType(evolvingArrayType) { @@ -29126,8 +29220,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 16384)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -29168,10 +29262,7 @@ var ts; var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } + return apparentType !== unknownType && ts.some(getSignaturesOfType(apparentType, 0), signatureHasTypePredicate); } } return false; @@ -29380,7 +29471,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 : 1), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); @@ -29397,7 +29488,7 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1), true); } } var antecedentTypes = []; @@ -29427,7 +29518,7 @@ var ts; break; } } - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 : 1); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, true); } @@ -29458,6 +29549,23 @@ var ts; } return type; } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (131072 | 65536)) || (type.flags & 32768 && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { case 58: @@ -29469,10 +29577,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 && right_1.kind === 9) { + if (left_1.kind === 190 && (right_1.kind === 9 || right_1.kind === 13)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 && left_1.kind === 9) { + if (right_1.kind === 190 && (left_1.kind === 9 || left_1.kind === 13)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -29493,6 +29601,12 @@ var ts; break; case 93: return narrowTypeByInstanceof(type, expr, assumeTrue); + case 92: + var target = getReferenceCandidate(expr.right); + if ((expr.left.kind === 9 || expr.left.kind === 13) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; case 26: return narrowType(type, expr.right, assumeTrue); } @@ -29570,7 +29684,7 @@ var ts; var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); var caseType = discriminantType.flags & 16384 ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -29637,7 +29751,7 @@ var ts; return type; } var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; + var predicate = getTypePredicateOfSignature(signature); if (!predicate) { return type; } @@ -29757,18 +29871,24 @@ var ts; var parent = node.parent; return parent.kind === 180 || parent.kind === 182 && parent.expression === node || - parent.kind === 181 && parent.expression === node; + parent.kind === 181 && parent.expression === node || + parent.kind === 204 || + parent.kind === 177 && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } - function getDeclaredOrApparentType(symbol, node) { - var type = getTypeOfSymbol(symbol); + function getApparentTypeForLocation(type, node) { if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } return type; } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -29787,8 +29907,8 @@ var ts; getNodeLinks(container).flags |= 8192; return getTypeOfSymbol(symbol); } - if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; @@ -29823,7 +29943,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3)) { @@ -29854,12 +29974,13 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); while (flowContainer !== declarationContainer && (flowContainer.kind === 187 || flowContainer.kind === 188 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 247) || node.parent.kind === 204 || @@ -30015,6 +30136,14 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 187 && @@ -30045,10 +30174,6 @@ var ts; return type; } } - if (noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -30238,7 +30363,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -30259,7 +30384,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); indexOfParameter -= 1; @@ -30278,7 +30403,7 @@ var ts; } function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer || node.kind === 58) { + if (ts.hasInitializer(declaration) && node === declaration.initializer) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -30362,7 +30487,7 @@ var ts; } function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); @@ -30387,11 +30512,6 @@ var ts; case 53: case 26: return node === right ? getContextualType(binaryExpression) : undefined; - case 34: - case 32: - case 35: - case 33: - return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; default: return undefined; } @@ -30416,10 +30536,10 @@ var ts; return mapType(type, function (t) { var prop = t.flags & 458752 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; - }); + }, true); } function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, true); } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 131072 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); @@ -30544,11 +30664,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 198: return getContextualTypeForYieldOperand(parent); - case 183: - if (node.kind === 94) { - return getContextualType(parent); - } case 182: + case 183: return getContextualTypeForArgument(parent, node); case 185: case 203: @@ -30582,12 +30699,6 @@ var ts; case 252: case 251: return getAttributesTypeFromJsxOpeningLikeElement(parent); - case 261: { - if (node.kind === 73) { - var switchStatement = parent.parent.parent; - return getTypeOfExpression(switchStatement.expression); - } - } } return undefined; } @@ -30596,7 +30707,7 @@ var ts; return node ? node.contextualMapper : identityMapper; } function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); + var signatures = getSignaturesOfType(type, 0); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -30642,8 +30753,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -30660,7 +30771,6 @@ var ts; var result; if (signatureList) { result = cloneSignature(signatureList[0]); - result.resolvedReturnType = undefined; result.unionSignatures = signatureList; } return result; @@ -30718,7 +30828,7 @@ var ts; if (patternElement.kind !== 201) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -30728,7 +30838,7 @@ var ts; } } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : + getUnionType(elementTypes, 2) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { @@ -30775,7 +30885,7 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, 2) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, checkMode) { @@ -30784,7 +30894,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 0; + var propagatedFlags = 2097152; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 175 || contextualType.pattern.kind === 179); @@ -30942,12 +31052,12 @@ var ts; type.flags & 65536 && !isGenericMappedType(type) || type.flags & 393216 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node); + function checkJsxSelfClosingElement(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); return getJsxGlobalElementType() || anyType; } - function checkJsxElement(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + function checkJsxElement(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); } @@ -30956,8 +31066,8 @@ var ts; } return getJsxGlobalElementType() || anyType; } - function checkJsxFragment(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + function checkJsxFragment(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) { error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); } @@ -30977,11 +31087,15 @@ var ts; ts.Debug.fail(); } } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; + } + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); var spread = emptyObjectType; - var attributesArray = []; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; @@ -30990,9 +31104,7 @@ var ts; var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; + var exprType = checkJsxAttribute(attributeDecl, checkMode); var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -31002,24 +31114,22 @@ var ts; attributeSymbol.type = exprType; attributeSymbol.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); - attributesArray.push(attributeSymbol); if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } } else { ts.Debug.assert(attributeDecl.kind === 259); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); - attributesArray = []; + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpression(attributeDecl.expression); + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 67108864); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -31027,18 +31137,8 @@ var ts; } } if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createSymbolTable(); - for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { - var attr = attributesArray_1[_b]; - if (!filter || filter(attr)) { - attributesTable.set(attr.escapedName, attr); - } + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864); } } var parent = openingLikeElement.parent.kind === 250 ? openingLikeElement.parent : undefined; @@ -31051,18 +31151,18 @@ var ts; var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + createArrayType(getUnionType(childrenTypes)); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, 67108864); } } if (hasSpreadAnyType) { return anyType; } - var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); - return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : - typeToIntersect ? typeToIntersect : attributeType; - function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + function createJsxAttributesType() { + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); result.flags |= 67108864 | 8388608; result.objectFlags |= 128; return result; @@ -31084,7 +31184,7 @@ var ts; return childrenTypes; } function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } function getJsxType(name) { var jsxType = jsxTypes.get(name); @@ -31122,7 +31222,7 @@ var ts; } return links.resolvedSymbol; } - function getJsxElementInstanceType(node, valueType) { + function getJsxElementInstanceType(node, valueType, sourceAttributesType) { ts.Debug.assert(!(valueType.flags & 131072)); if (isTypeAny(valueType)) { return anyType; @@ -31135,19 +31235,25 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0, isJavascript); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); + } + else { + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -31260,13 +31366,12 @@ var ts; } return undefined; } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { if (elementType.flags & 131072) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), true); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + }), 2); } if (elementType.flags & 2) { return anyType; @@ -31287,14 +31392,14 @@ var ts; } return anyType; } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); if (statelessAttributesType) { return statelessAttributesType; } - if (elementClassType) { + if (elementClassType && sourceAttributesType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } if (isTypeAny(elemInstanceType)) { @@ -31354,21 +31459,26 @@ var ts; } return links.resolvedJsxElementAttributesType; } - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { + if (!sourceAttributesType) { + var links = getNodeLinks(node); + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { + var elemClassType = getJsxGlobalElementClassType(); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); + } + return links[linkLocation]; + } + else { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } - return links[linkLocation]; } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, true); + return getCustomJsxElementAttributesType(node, undefined, true); } } function getAttributesTypeFromJsxOpeningLikeElement(node) { @@ -31376,7 +31486,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, false); + return getCustomJsxElementAttributesType(node, undefined, false); } } function getJsxAttributePropertySymbol(attrib) { @@ -31419,7 +31529,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node) { + function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -31436,7 +31546,7 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node); + checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); } else { checkJsxChildren(node.parent); @@ -31462,13 +31572,11 @@ var ts; } return false; } - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, false); - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); - }); + getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, false); if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); } @@ -31477,8 +31585,13 @@ var ts; if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; - if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); + if (!ts.isJsxAttribute(attribute)) { + continue; + } + var attrName = attribute.name; + var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); break; } } @@ -31574,16 +31687,16 @@ var ts; return propKind !== 152 && propKind !== 151; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288; if (kind) { - error(errorNode, kind & 4096 ? kind & 8192 ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 ? kind & 8192 ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 | 16384) ? unknownType : t; } @@ -31597,15 +31710,20 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var propType; - var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; var apparentType = getApparentType(getWidenedType(leftType)); if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } return apparentType; } var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0); if (!(indexInfo && indexInfo.type)) { @@ -31622,11 +31740,6 @@ var ts; else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99); - leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && - !(isNonLocalAlias(leftSymbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { - getSymbolLinks(leftSymbol).referenced = undefined; - } getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); if (assignmentKind) { @@ -31635,7 +31748,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } if (node.kind !== 180 || assignmentKind === 1 || @@ -31689,6 +31802,9 @@ var ts; }); } function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32)) { + return false; + } var classType = getTypeOfSymbol(prop.parent); while (true) { classType = getSuperClass(classType); @@ -31735,7 +31851,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); @@ -31817,31 +31933,42 @@ var ts; return res > max ? undefined : res; } 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; - } - else { - prop.isReferenced = true; + if (!prop || !noUnusedIdentifiers || !(prop.flags & 106500) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 && !(prop.flags & 32768))) { + return; + } + 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; + } + else { + prop.isReferenced = true; + } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 180 - ? node.expression - : node.left; + var left = node.kind === 180 ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + && (!(property.flags & 8192) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, type) { + var propType = getTypeOfFuncClassEnumModule(method); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var thisType = getThisTypeOfSignature(sig); + return !thisType || isTypeAssignableTo(type, thisType); + }); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(type, propertyName); @@ -32094,10 +32221,15 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } + function inferJsxTypeArguments(signature, sourceAttributesType, context) { + var paramType = getTypeAtPosition(signature, 0); + inferTypes(context.inferences, sourceAttributesType, paramType); + return getInferredTypes(context); + } function inferTypeArguments(node, signature, args, excludeArgument, context) { for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { var inference = _a[_i]; @@ -32114,7 +32246,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); } } var thisType = getThisTypeOfSignature(signature); @@ -32157,7 +32289,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -32557,7 +32689,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, true)] = false; + excludeArgument[excludeArgument.indexOf(true)] = false; } else { excludeArgument = undefined; @@ -32594,7 +32726,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -32615,7 +32747,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); } return resolveErrorCall(node); } @@ -32669,7 +32801,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -32707,6 +32839,24 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -32719,7 +32869,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -32761,6 +32911,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -32780,8 +32931,8 @@ var ts; if (elementType.flags & 131072) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -32927,16 +33078,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default")) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152, "default"); newSymbol.target = resolveSymbol(symbol); @@ -32944,7 +33097,7 @@ var ts; var anonymousSymbol = createSymbol(2048, "__type"); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 && type.symbol.flags & (1536 | 3)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -33022,7 +33175,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks) { var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { + if (declaration && ts.hasInitializer(declaration)) { return getOptionalType(type); } } @@ -33125,7 +33278,6 @@ var ts; return promiseType; } function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } @@ -33138,9 +33290,9 @@ var ts; } } else { - var types = void 0; + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (functionFlags & 1) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 ? createAsyncIterableIteratorType(anyType) @@ -33152,7 +33304,6 @@ var ts; } } else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) { return functionFlags & 2 ? createPromiseReturnType(func, neverType) @@ -33164,8 +33315,9 @@ var ts; : voidType; } } - type = getUnionType(types, true); + type = getUnionType(types, 2); } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!contextualSignature) { reportErrorsFromWidening(func, type); } @@ -33264,8 +33416,7 @@ var ts; hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 187 || func.kind === 188)) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -33273,6 +33424,17 @@ var ts; } return aggregatedTypes; } + function mayReturnNever(func) { + switch (func.kind) { + case 187: + case 188: + return true; + case 152: + return func.parent.kind === 179; + default: + return false; + } + } function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; @@ -33522,8 +33684,8 @@ var ts; } if (type.flags & 393216) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33588,6 +33750,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -33899,7 +34064,7 @@ var ts; leftType; case 54: return getTypeFacts(leftType) & 2097152 ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], true) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : leftType; case 58: checkAssignmentOperator(rightType); @@ -34015,7 +34180,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getUnionType([type1, type2], true); + return getUnionType([type1, type2], 2); } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -34029,7 +34194,7 @@ var ts; node.contextualType = contextualType; node.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 : - contextualMapper ? 2 : 0; + contextualMapper ? 2 : 3; var result = checkExpression(node, checkMode); node.contextualType = saveContextualType; node.contextualMapper = saveContextualMapper; @@ -34038,6 +34203,9 @@ var ts; function checkExpressionCached(node, checkMode) { var links = getNodeLinks(node); if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } var saveFlowLoopStart = flowLoopStart; flowLoopStart = flowLoopCount; links.resolvedType = checkExpression(node, checkMode); @@ -34057,10 +34225,10 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 131072 && !(contextualType.flags & 8)) { - var types_19 = contextualType.types; - return ts.some(types_19, function (t) { - return !(t.flags & 128 && containsType(types_19, trueType) && containsType(types_19, falseType)) && + if (contextualType.flags & 393216 && !(contextualType.flags & 8)) { + var types_18 = contextualType.types; + return ts.some(types_18, function (t) { + return !(t.flags & 128 && containsType(types_18, trueType) && containsType(types_18, falseType)) && isLiteralOfContextualType(candidateType, t); }); } @@ -34145,9 +34313,10 @@ var ts; if (isConstEnumObjectType(type)) { var ok = (node.parent.kind === 180 && node.parent.expression === node) || (node.parent.kind === 181 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -34238,11 +34407,11 @@ var ts; case 260: return checkJsxExpression(node, checkMode); case 250: - return checkJsxElement(node); + return checkJsxElement(node, checkMode); case 251: - return checkJsxSelfClosingElement(node); + return checkJsxSelfClosingElement(node, checkMode); case 254: - return checkJsxFragment(node); + return checkJsxFragment(node, checkMode); case 258: return checkJsxAttributes(node, checkMode); case 252: @@ -34285,7 +34454,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 || func.kind === 157 || func.kind === 162) { @@ -34313,7 +34482,7 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); if (!typePredicate) { return; } @@ -34328,7 +34497,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); } } @@ -34614,22 +34783,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 && !ts.hasModifier(n, 32) && @@ -34818,6 +34971,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -35127,7 +35283,7 @@ var ts; } return undefined; } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2); } function checkAwaitedType(type, errorNode, diagnosticMessage) { return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; @@ -35153,7 +35309,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { if (errorNode) { error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); } @@ -35259,7 +35415,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } function markTypeNodeAsReferenced(node) { markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); @@ -35572,22 +35728,33 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 152 || member.kind === 150) { - if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152: + case 150: + case 154: + case 155: + if (member.kind === 155 && member.symbol.flags & 32768) { + break; } - } - else if (member.kind === 153) { + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } - } + break; + case 158: + break; + default: + ts.Debug.fail(); } } } @@ -35840,7 +36007,9 @@ var ts; } function checkVariableLikeDeclaration(node) { checkDecorators(node); - checkSourceElement(node.type); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } if (!node.name) { return; } @@ -35878,13 +36047,19 @@ var ts; } if (ts.isBindingPattern(node.name)) { if (node.initializer && node.parent.parent.kind !== 216) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + } checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 216) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -36112,7 +36287,7 @@ var ts; var arrayTypes = inputType.types; var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322); }); if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, true); + arrayType = getUnionType(filteredTypes, 2); } } else if (arrayType.flags & 524322) { @@ -36149,7 +36324,7 @@ var ts; if (arrayElementType.flags & 524322) { return stringType; } - return getUnionType([arrayElementType, stringType], true); + return getUnionType([arrayElementType, stringType], 2); } return arrayElementType; } @@ -36193,7 +36368,7 @@ var ts; } return undefined; } - var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, !!asyncMethodType); if (checkAssignability && errorNode && iteratedType) { checkTypeAssignableTo(type, asyncMethodType @@ -36232,7 +36407,7 @@ var ts; } return undefined; } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2); if (isTypeAny(nextResult)) { return undefined; } @@ -36277,49 +36452,49 @@ var ts; return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); } function checkReturnStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } + if (checkGrammarStatementInAmbientContext(node)) { + return; } var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1; + if (strictNullChecks || node.expression || returnType.flags & 16384) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { return; } - if (strictNullChecks || node.expression || returnType.flags & 16384) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 155) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } + else if (func.kind === 155) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 153) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } + } + else if (func.kind === 153) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + checkTypeAssignableTo(awaitedType, promisedType, node); } } - } - else if (func.kind !== 153 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + else { + checkTypeAssignableTo(exprType, returnType, node); + } } } + else if (func.kind !== 153 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -36464,7 +36639,7 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -36565,9 +36740,10 @@ var ts; } var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; + if (sourceConstraint) { + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } } var sourceDefault = source.default && getTypeFromTypeNode(source.default); var targetDefault = getDefaultFromTypeParameter(target); @@ -36637,7 +36813,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -36663,7 +36842,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + var genericDiag = t.symbol && t.symbol.flags & 32 ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -36678,6 +36863,32 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1); if (signatures.length) { @@ -36944,6 +37155,7 @@ var ts; case 37: return left + right; case 38: return left - right; case 42: return left % right; + case 40: return Math.pow(left, right); } } break; @@ -38035,6 +38247,7 @@ var ts; } return undefined; case 9: + case 13: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 239 || node.parent.kind === 245) && node.parent.moduleSpecifier === node) || ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { @@ -38131,7 +38344,7 @@ var ts; ts.Debug.assert(expr.parent.kind === 178); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } function getPropertySymbolOfDestructuringAssignment(location) { var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); @@ -38165,35 +38378,28 @@ var ts; return ts.typeHasCallOrConstructSignatures(type, checker); } function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6) { - var symbols_4 = []; - var name_4 = symbol.escapedName; - ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_4); - if (symbol) { - symbols_4.push(symbol); - } - }); - return symbols_4; + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); } else if (symbol.flags & 33554432) { - var transient = symbol; - if (transient.leftSpread) { - return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); - } - if (transient.syntheticOrigin) { - return getRootSymbols(transient.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; } - return [symbol]; + return target; } function isArgumentsLocalBinding(node) { if (!ts.isGeneratedIdentifier(node)) { @@ -38482,20 +38688,20 @@ var ts; : unknownType; if (type.flags & 1024 && type.symbol === symbol) { - flags |= 131072; + flags |= 1048576; } - if (flags & 8192) { + if (flags & 131072) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -39060,9 +39266,6 @@ var ts; } } function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } if (typeParameters && typeParameters.length === 0) { var start = typeParameters.pos - "<".length; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; @@ -39145,6 +39348,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 || type.flags & 4) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32, true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -39560,12 +39770,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 || node.name.kind === 175) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } @@ -39750,7 +39963,7 @@ var ts; if (node.flags & 2097152 && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 2097152 || ts.hasModifier(node, 32 | 128))) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } @@ -39971,7 +40184,7 @@ var ts; var node = createSynthesizedNode(71); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; - node.autoGenerateKind = 0; + node.autoGenerateFlags = 0; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -39986,20 +40199,23 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1; + name.autoGenerateFlags = 1; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16; + } return name; } ts.createTempVariable = createTempVariable; function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2; + name.autoGenerateFlags = 2; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -40007,7 +40223,7 @@ var ts; ts.createLoopVariable = createLoopVariable; function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3; + name.autoGenerateFlags = 3; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -40015,10 +40231,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4; + name.autoGenerateFlags = 4; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8; + } nextAutoGenerateId++; return name; } @@ -40310,11 +40528,12 @@ var ts; : node; } ts.updateIndexSignature = updateIndexSignature; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -42921,7 +43140,9 @@ var ts; } ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; function parenthesizeSubexpressionOfConditionalExpression(e) { - return e.kind === 195 && e.operatorToken.kind === 26 + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 && emittedExpression.operatorToken.kind === 26 || + emittedExpression.kind === 293 ? ts.createParen(e) : e; } @@ -43410,6 +43631,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -43519,7 +43741,7 @@ var ts; } switch (kind) { case 71: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145: @@ -43659,7 +43881,7 @@ var ts; case 216: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219: @@ -44397,6 +44619,7 @@ var ts; var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -44471,7 +44694,10 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + value = ensureIdentifier(flattenContext, value, false, location); + } + else if (needsValue) { value = ensureIdentifier(flattenContext, value, true, location); } else if (ts.nodeIsSynthesized(node)) { @@ -44501,6 +44727,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { var pendingExpressions; var pendingDeclarations = []; @@ -44517,6 +44763,13 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + initializer = ensureIdentifier(flattenContext, initializer, false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(undefined); @@ -45165,10 +45418,13 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16; + classAliases[ts.getOriginalNodeId(node)] = alias; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); @@ -46461,12 +46717,13 @@ var ts; var ts; (function (ts) { function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var enabledSubstitutions; var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -46501,6 +46758,82 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209: + return visitVariableStatementInAsyncBody(node); + case 215: + return visitForStatementInAsyncBody(node); + case 216: + return visitForInStatementInAsyncBody(node); + case 217: + return visitForOfStatementInAsyncBody(node); + case 264: + return visitCatchClauseInAsyncBody(node); + case 208: + case 222: + case 236: + case 261: + case 262: + case 225: + case 213: + case 214: + case 212: + case 221: + case 223: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } function visitAwaitExpression(node) { return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } @@ -46524,6 +46857,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -46531,10 +46931,17 @@ var ts; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; var isArrowFunction = node.kind === 188; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); @@ -46548,27 +46955,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -46794,7 +47202,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2) { var statement = ts.unwrapInnermostStatementOfLabel(node); if (statement.kind === 217 && statement.awaitModifier) { return visitForOfStatement(statement, node); @@ -46806,8 +47214,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -47222,7 +47630,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncIterator) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -48106,7 +48514,7 @@ var ts; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), extendsClauseElement)); + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), extendsClauseElement)); } } function addConstructor(statements, node, extendsClauseElement) { @@ -51440,7 +51848,7 @@ var ts; var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), @@ -51452,6 +51860,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; @@ -51475,7 +51885,7 @@ var ts; ]))) ]))) ], true), undefined)); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, undefined, [ ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ ts.createParameter(undefined, undefined, undefined, "require"), @@ -51483,6 +51893,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ])) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function collectAsynchronousDependencies(node, includeNonAmdDependencies) { var aliasedModuleNames = []; @@ -51515,6 +51927,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); var statements = []; @@ -51523,6 +51946,9 @@ var ts; ts.append(statements, createUnderscoreUnderscoreESModule()); } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); ts.addRange(statements, endLexicalEnvironment()); @@ -51633,11 +52059,20 @@ var ts; ts.setEmitFlags(func, 8); } } - return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), undefined, [requireCall]); + } var func; if (languageVersion >= 2) { func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); @@ -51650,6 +52085,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]); + } + return innerExpr; + } function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); @@ -51660,10 +52109,10 @@ var ts; else { var variables = []; if (namespaceDeclaration && !ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); } @@ -52125,6 +52574,16 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -52138,6 +52597,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); + context.enableSubstitution(266); context.enableSubstitution(195); context.enableSubstitution(193); context.enableSubstitution(194); @@ -52853,6 +53313,31 @@ var ts; if (hint === 1) { return substituteExpression(node); } + else if (hint === 4) { + return substituteUnspecified(node); + } + return node; + } + function substituteUnspecified(node) { + switch (node.kind) { + case 266: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), node); + } + } + } return node; } function substituteExpression(node) { @@ -52979,7 +53464,9 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + var tslibImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -53468,9 +53955,9 @@ var ts; setSourceFile(oldSource); } } - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -53479,7 +53966,7 @@ var ts; if ((emitFlags & 128) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256) === 0 && tokenPos >= 0) { @@ -53495,7 +53982,7 @@ var ts; currentSourceText = currentSource.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -53975,7 +54462,7 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { write("export {};"); writeLine(); } @@ -54135,9 +54622,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 | - 16384 | - (shouldUseResolverType ? 8192 : 0); + var format = 4096 | 8 | 4 | + 2048 | + (shouldUseResolverType ? 131072 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -54150,7 +54637,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); errorNameNode = undefined; } } @@ -54380,12 +54867,15 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); write(";"); writeLine(); return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; + } if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -54468,6 +54958,7 @@ var ts; if (node.parent.kind === 269) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { + resultHasExternalModuleIndicator = true; write("export "); } if (modifiers & 512) { @@ -54600,6 +55091,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -55014,7 +55506,7 @@ var ts; } } function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - if (node.type) { + if (ts.hasType(node)) { write(": "); emitType(node.type); } @@ -55517,7 +56009,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -55542,7 +56034,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); @@ -55552,7 +56043,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -55561,7 +56055,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -55675,7 +56172,7 @@ var ts; } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -55735,14 +56232,27 @@ var ts; var generatedNames; var tempFlagsStack; var tempFlags; + var reservedNamesStack; + var reservedNames; var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -55765,6 +56275,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -55780,6 +56294,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -55807,7 +56331,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -55833,6 +56357,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0; + reservedNamesStack = []; comments.reset(); setWriter(undefined); } @@ -55894,13 +56419,15 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -56120,7 +56647,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -56141,7 +56668,7 @@ var ts; case 101: case 99: case 91: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; case 178: return emitArrayLiteralExpression(node); @@ -56224,19 +56751,20 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + writeStringLiteral(text); } } function emitIdentifier(node) { - write(getTextOfNode(node, false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, false), node.symbol); + emitList(node, node.typeArguments, 26896); } function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -56248,51 +56776,61 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -56301,8 +56839,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -56314,13 +56852,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 ? "get " : "set "); + writeKeyword(node.kind === 154 ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -56329,31 +56868,34 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -56363,7 +56905,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -56385,34 +56929,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; emitList(node, node.members, flags | 262144); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260); @@ -56421,29 +56970,29 @@ var ts; emitList(node, node.types, 264); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -56451,54 +57000,47 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); } function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432); - write("}"); - } + writePunctuation("{"); + emitList(node, node.elements, 262576); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304); - write("]"); - } + writePunctuation("["); + emitList(node, node.elements, 262448); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitArrayLiteralExpression(node) { var elements = node.elements; @@ -56532,7 +57074,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -56553,9 +57095,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -56563,26 +57105,27 @@ var ts; emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -56595,30 +57138,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -56630,7 +57177,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26; @@ -56639,7 +57186,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, true); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -56667,12 +57214,12 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -56685,17 +57232,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } function emitTemplateSpan(node) { @@ -56703,12 +57252,12 @@ var ts; emit(node.literal); } function emitBlock(node) { - writeToken(17, node.pos, node); + writeToken(17, node.pos, writePunctuation, node); emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18, node.statements.end, node); + writeToken(18, node.statements.end, writePunctuation, node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; @@ -56717,27 +57266,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90, node.pos, node); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(90, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, node); + writeToken(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82, node.thenStatement.end, node); + writeToken(82, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -56746,55 +57295,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -56808,58 +57365,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, contextNode); + pos = writeToken(token, pos, writer, contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96, node.pos, node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(98, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20, node.expression.end); - write(" "); + writeToken(20, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -56867,21 +57428,23 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78, node.pos); - write(";"); + writeToken(78, node.pos, writeKeyword); + writeSemicolon(); } function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272); } function emitFunctionDeclaration(node) { @@ -56890,9 +57453,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -56922,19 +57485,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { if (ts.getEmitFlags(body) & 1) { @@ -56961,7 +57524,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -56973,7 +57537,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18, body.statements.end, body); + writeToken(18, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -56997,17 +57561,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -57015,66 +57583,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512) { - write(node.flags & 16 ? "namespace " : "module "); + writeKeyword(node.flags & 16 ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17, node.pos); + writeToken(17, node.pos, writePunctuation); emitList(node, node.clauses, 65); - writeToken(18, node.clauses.end); + writeToken(18, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71) { @@ -57086,23 +57665,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -57112,28 +57698,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -57142,21 +57744,24 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitJsxElement(node) { emit(node.openingElement); @@ -57164,13 +57769,13 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -57178,44 +57783,45 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -57227,13 +57833,15 @@ var ts; } } function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -57246,31 +57854,32 @@ var ts; } var format = 81985; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 | 64); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272); } function emitCatchClause(node) { - var openParenPos = writeToken(74, node.pos); - write(" "); + var openParenPos = writeToken(74, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19, openParenPos); + writeToken(19, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration.end); - write(" "); + writeToken(20, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); var initializer = node.initializer; if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512) === 0) { var commentRange = ts.getCommentRange(initializer); @@ -57281,19 +57890,21 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitSourceFile(node) { writeLine(); @@ -57376,33 +57987,60 @@ var ts; } } } + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } } - function emitNodeWithPrefix(prefix, node, emit) { + function emitWithLeadingSpace(node) { if (node) { - write(prefix); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1) { - write(" "); + writeSpace(); emit(node); } else { @@ -57416,13 +58054,16 @@ var ts; emitList(parentNode, decorators, 24577); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960); + emitList(parentNode, typeArguments, 26896); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360); + emitList(parentNode, parameters, 1296); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -57442,7 +58083,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 & ~1024); + emitList(parentNode, parameters, 1296 & ~1024); } else { emitParameters(parentNode, parameters); @@ -57457,6 +58098,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28) { + case 0: + break; + case 16: + writePunctuation(","); + break; + case 4: + writeSpace(); + writePunctuation("|"); + break; + case 8: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -57475,7 +58133,7 @@ var ts; return; } if (format & 7680) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -57485,7 +58143,7 @@ var ts; writeLine(); } else if (format & 128 && !(format & 262144)) { - write(" "); + writeSpace(); } } else { @@ -57496,21 +58154,20 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128) { - write(" "); + writeSpace(); } if (format & 64) { increaseIndent(); } var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { if ((format & (3 | 64)) === 0) { increaseIndent(); @@ -57520,7 +58177,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256) { - write(" "); + writeSpace(); } } if (shouldEmitInterveningComments) { @@ -57541,9 +58198,9 @@ var ts; } var hasTrailingComma = (format & 32) && children.hasTrailingComma; if (format & 16 && hasTrailingComma) { - write(","); + writePunctuation(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { + if (previousSibling && format & 28 && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } if (format & 64) { @@ -57553,50 +58210,102 @@ var ts; writeLine(); } else if (format & 128) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -57779,16 +58488,24 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } function popNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } function generateName(name) { - if (name.autoGenerateKind === 4) { - if (name.skipNameGenerationScope) { + if ((name.autoGenerateFlags & 7) === 4) { + if (name.autoGenerateFlags & 8) { var savedTempFlags = tempFlags; popNameGenerationScope(undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -57812,7 +58529,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { @@ -57825,11 +58543,14 @@ var ts; } return true; } - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -57841,6 +58562,9 @@ var ts; ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -57907,11 +58631,11 @@ var ts; } } function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7) { case 1: - return makeTempVariableName(0); + return makeTempVariableName(0, !!(name.autoGenerateFlags & 16)); case 2: - return makeTempVariableName(268435456); + return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); case 3: return makeUniqueName(ts.idText(name)); } @@ -57924,7 +58648,7 @@ var ts; while (original) { node = original; if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 + && node.autoGenerateFlags === 4 && node.autoGenerateId !== autoGenerateId) { break; } @@ -57934,17 +58658,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0] = ""; - delimiters[16] = ","; - delimiters[4] = " |"; - delimiters[8] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28]; - } function createBracketsMap() { var brackets = []; brackets[512] = ["{", "}"]; @@ -57962,6 +58675,168 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + if (!host.directoryExists) { + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; var ConfigFileProgramReloadLevel; (function (ConfigFileProgramReloadLevel) { ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; @@ -57998,6 +58873,13 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -58073,346 +58955,6 @@ var ts; ts.closeFileWatcherOf = closeFileWatcherOf; })(ts || (ts = {})); var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - function createBuilder(options) { - var isModuleEmit; - var fileInfos = ts.createMap(); - var semanticDiagnosticsPerFile = ts.createMap(); - var changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - 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) { - changedFilesSet.set(path, true); - semanticDiagnosticsPerFile.delete(path); - } - function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - 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); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - 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)]; - } - var seenFiles = ts.createMap(); - 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)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - 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]; - 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(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - 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 = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - 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) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function getFilesAffectedByUpdatedShape(program, sourceFile) { - var options = program.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.mapDefinedIter(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - }); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFile]; - } - var seenFileNamesMap = ts.createMap(); - var path = sourceFile.path; - 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); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); - } - } - } - ts.createBuilder = createBuilder; -})(ts || (ts = {})); -var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { @@ -58595,23 +59137,29 @@ var ts; return errorMessage; } ts.formatDiagnostic = formatDiagnostic; - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } - function formatAndReset(text, formatStyle) { + function formatColorAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } + ts.formatColorAndReset = formatColorAndReset; function padLeft(s, length) { while (s.length < length) { s = " " + s; @@ -58624,9 +59172,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -58637,7 +59185,7 @@ var ts; context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -58645,10 +59193,10 @@ var ts; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); - context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); - context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += redForegroundEscapeSequence; + context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += ForegroundColorEscapeSequences.Red; if (i === firstLine) { var lastCharForLine = i === lastLine ? lastLineChar : undefined; context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); @@ -58662,19 +59210,25 @@ var ts; } context += resetEscapeSequence; } - output += host.getNewLine(); - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + output += " - "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); output += context; } output += host.getNewLine(); } - return output; + return output + host.getNewLine(); } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { @@ -58882,7 +59436,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -58987,8 +59542,9 @@ var ts; ts.Debug.assert(j === resolutions.length); return result; function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); - if (resolutionToFile) { + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { return false; } var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); @@ -59107,7 +59663,7 @@ var ts; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -59205,24 +59761,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -59544,6 +60102,7 @@ var ts; && !file.isDeclarationFile) { var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(undefined, undefined, undefined); + ts.addEmitFlags(importDecl, 67108864); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -59711,7 +60270,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); @@ -59823,7 +60382,7 @@ var ts; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { @@ -60042,12 +60601,12 @@ var ts; if (emitFileName) { var emitFilePath = toPath(emitFileName); if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { - chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; if (emitFilesSeen.has(emitFileKey)) { @@ -60141,6 +60700,31 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts"); + } + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts")) || + !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx")); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } } ts.createProgram = createProgram; function getResolutionDiagnostic(options, _a) { @@ -60181,9 +60765,522 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +(function (ts) { + var BuilderState; + (function (BuilderState) { + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + function getAllDependencies(state, programOfThisState, sourceFile) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + var seenFileNamesMap = ts.createMap(); + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + if (map1 === undefined) { + return map2 === undefined; + } + if (map2 === undefined) { + return map1 === undefined; + } + return map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState && oldState.referencedMap; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + if (!useOldState || + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + oldInfo.version !== info.version || + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + return undefined; + } + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var host; + var newProgram; + if (ts.isArray(newProgramOrRootNames)) { + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program) { + newProgram = undefined; + oldState = undefined; + return oldProgram; + } + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + newProgram = undefined; + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + return undefined; + } + return toAffectedFileResult(state, state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + var sourceMaps = []; + var emitSkipped = void 0; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + return undefined; + } + else if (affected === state.program) { + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(undefined, cancellationToken), affected); + } + if (ignoreSourceFile && ignoreSourceFile(affected)) { + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; + return { + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +var ts; (function (ts) { ts.maxNumberOfFilesToIterateForInvalidation = 256; - function createResolutionCache(resolutionHost, rootDirForResolution) { + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; @@ -60192,6 +61289,7 @@ var ts; var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); @@ -60241,8 +61339,8 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } - function createHasInvalidatedResolution() { - if (allFilesHaveInvalidatedResolution) { + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { filesWithInvalidatedResolutions = undefined; return ts.returnTrue; } @@ -60353,8 +61451,8 @@ var ts; function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, undefined, false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); @@ -60475,8 +61573,8 @@ var ts; function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } if (!allFilesHaveInvalidatedResolution && dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { @@ -60554,6 +61652,9 @@ var ts; if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { return false; } + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } } @@ -60568,8 +61669,8 @@ var ts; function createTypeRootsWatch(_typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } resolutionHost.onChangedAutomaticTypeDirectiveNames(); }, 1); @@ -60601,91 +61702,109 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var defaultFormatDiagnosticsHost = ts.sys ? { + var sysFormatDiagnosticsHost = ts.sys ? { getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, getNewLine: function () { return ts.sys.newLine; }, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) } : undefined; - function createDiagnosticReporter(system, worker, formatDiagnosticsHost) { - if (system === void 0) { system = ts.sys; } - if (worker === void 0) { worker = reportDiagnosticSimply; } - return function (diagnostic) { return worker(diagnostic, getFormatDiagnosticsHost(), system); }; - function getFormatDiagnosticsHost() { - return formatDiagnosticsHost || (formatDiagnosticsHost = system === ts.sys ? defaultFormatDiagnosticsHost : { - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, - getNewLine: function () { return system.newLine; }, - getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), - }); + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; } - } - ts.createDiagnosticReporter = createDiagnosticReporter; - function createWatchDiagnosticReporter(system) { - if (system === void 0) { system = ts.sys; } + var diagnostics = new Array(1); return function (diagnostic) { - var output = new Date().toLocaleTimeString() + " - "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine + system.newLine); - system.write(output); + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; }; } - ts.createWatchDiagnosticReporter = createWatchDiagnosticReporter; - function reportDiagnostics(diagnostics, reportDiagnostic) { - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; - reportDiagnostic(diagnostic); - } - } - ts.reportDiagnostics = reportDiagnostics; - function reportDiagnosticSimply(diagnostic, host, system) { - system.write(ts.formatDiagnostic(diagnostic, host)); + ts.createDiagnosticReporter = createDiagnosticReporter; + function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { + if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + system.clearScreen(); + } + } + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + }; } - ts.reportDiagnosticSimply = reportDiagnosticSimply; - function reportDiagnosticWithColorAndContext(diagnostic, host, system) { - system.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + host.getNewLine()); + ts.createWatchStatusReporter = createWatchStatusReporter; + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onConfigFileDiagnostic = undefined; + host.onUnRecoverableConfigFileDiagnostic = undefined; + return result; } - ts.reportDiagnosticWithColorAndContext = reportDiagnosticWithColorAndContext; - function parseConfigFile(configFileName, optionsToExtend, system, reportDiagnostic, reportWatchDiagnostic) { + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { var configFileText; try { - configFileText = system.readFile(configFileName); + configFileText = host.readFile(configFileName); } catch (e) { var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - reportWatchDiagnostic(error); - system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; } if (!configFileText) { var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - reportDiagnostics([error], reportDiagnostic); - system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; } var result = ts.parseJsonText(configFileName, configFileText); - reportDiagnostics(result.parseDiagnostics, reportDiagnostic); - var cwd = system.getCurrentDirectory(); - var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, system, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - reportDiagnostics(configParseResult.errors, reportDiagnostic); + result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + var cwd = host.getCurrentDirectory(); + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); return configParseResult; } - ts.parseConfigFile = parseConfigFile; - function reportEmittedFiles(files, system) { - if (!files || files.length === 0) { - return; - } - var currentDir = system.getCurrentDirectory(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var file = files_2[_i]; - var filepath = ts.getNormalizedAbsolutePath(file, currentDir); - system.write("TSFILE: " + filepath + system.newLine); + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + var diagnostics = program.getSyntacticDiagnostics().slice(); + var reportSemanticDiagnostics = false; + if (diagnostics.length === 0) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + reportSemanticDiagnostics = true; + } } - } - function handleEmitOutputAndReportErrors(system, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic) { - reportDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), reportDiagnostic); - reportEmittedFiles(emittedFiles, system); - if (program.getCompilerOptions().listFiles) { - ts.forEach(program.getSourceFiles(), function (file) { - system.write(file.fileName + system.newLine); + var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } } if (emitSkipped && diagnostics.length > 0) { return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; @@ -60695,89 +61814,90 @@ var ts; } return ts.ExitStatus.Success; } - ts.handleEmitOutputAndReportErrors = handleEmitOutputAndReportErrors; - function createWatchingSystemHost(pretty, system, parseConfigFile, reportDiagnostic, reportWatchDiagnostic) { + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { if (system === void 0) { system = ts.sys; } - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system, pretty ? reportDiagnosticWithColorAndContext : reportDiagnosticSimply); - reportWatchDiagnostic = reportWatchDiagnostic || createWatchDiagnosticReporter(system); - parseConfigFile = parseConfigFile || ts.parseConfigFile; + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; return { - system: system, - parseConfigFile: parseConfigFile, - reportDiagnostic: reportDiagnostic, - reportWatchDiagnostic: reportWatchDiagnostic, - beforeCompile: ts.noop, - afterCompile: compileWatchedProgram, - }; - function compileWatchedProgram(host, program, builder) { - var diagnostics = program.getSyntacticDiagnostics().slice(); - var reportSemanticDiagnostics = false; - if (diagnostics.length === 0) { - ts.addRange(diagnostics, program.getOptionsDiagnostics()); - ts.addRange(diagnostics, program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { - reportSemanticDiagnostics = true; - } - } - var emittedFiles = program.getCompilerOptions().listEmittedFiles ? [] : undefined; - var sourceMaps; - var emitSkipped; - var result = builder.emitChangedFiles(program, writeFile); - if (result.length === 0) { - emitSkipped = true; - } - else { - for (var _i = 0, result_4 = result; _i < result_4.length; _i++) { - var emitOutput = result_4[_i]; - if (emitOutput.emitSkipped) { - emitSkipped = true; - } - ts.addRange(diagnostics, emitOutput.diagnostics); - sourceMaps = ts.concatenate(sourceMaps, emitOutput.sourceMaps); - } - } - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, builder.getSemanticDiagnostics(program)); - } - return handleEmitOutputAndReportErrors(host, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic); - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - if (emittedFiles) { - emittedFiles.push(fileName); - } - } - catch (e) { - if (onError) { - onError(e.message); - } + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; } - } + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + var _a; + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); } } - ts.createWatchingSystemHost = createWatchingSystemHost; - function createWatchModeWithConfigFile(configParseResult, optionsToExtend, watchingHost) { - if (optionsToExtend === void 0) { optionsToExtend = {}; } - return createWatchMode(configParseResult.fileNames, configParseResult.options, watchingHost, configParseResult.options.configFilePath, configParseResult.configFileSpecs, configParseResult.wildcardDirectories, optionsToExtend); + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } - ts.createWatchModeWithConfigFile = createWatchModeWithConfigFile; - function createWatchModeWithoutConfigFile(rootFileNames, compilerOptions, watchingHost) { - return createWatchMode(rootFileNames, compilerOptions, watchingHost); + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; } - ts.createWatchModeWithoutConfigFile = createWatchModeWithoutConfigFile; - function createWatchMode(rootFileNames, compilerOptions, watchingHost, configFileName, configFileSpecs, configFileWildCardDirectories, optionsToExtendForConfigFile) { - var program; + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + function createWatchProgram(host) { + var builderProgram; var reloadLevel; var missingFilesMap; var watchedWildcardDirectories; @@ -60786,83 +61906,116 @@ var ts; var missingFilePathsRequestedForRelease; var hasChangedCompilerOptions = false; var hasChangedAutomaticTypeDirectiveNames = false; - var loggingEnabled = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics; - var writeLog = loggingEnabled ? function (s) { system.write(s); system.write(system.newLine); } : ts.noop; + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; + var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onConfigFileDiagnostic: host.onConfigFileDiagnostic, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + }; + if (configFileName && !rootFileNames) { + parseConfigFile(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + var writeLog = loggingEnabled ? trace : ts.noop; var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; - watchingHost = watchingHost || createWatchingSystemHost(compilerOptions.pretty); - var system = watchingHost.system, parseConfigFile = watchingHost.parseConfigFile, reportDiagnostic = watchingHost.reportDiagnostic, reportWatchDiagnostic = watchingHost.reportWatchDiagnostic, beforeCompile = watchingHost.beforeCompile, afterCompile = watchingHost.afterCompile; - var directoryStructureHost = configFileName ? ts.createCachedDirectoryStructureHost(system) : system; if (configFileName) { - watchFile(system, configFileName, scheduleProgramReload, writeLog); + watchFile(host, configFileName, scheduleProgramReload, writeLog); } - var getCurrentDirectory = ts.memoize(function () { return directoryStructureHost.getCurrentDirectory(); }); - var realpath = system.realpath && (function (path) { return system.realpath(path); }); - var getCachedDirectoryStructureHost = configFileName && (function () { return directoryStructureHost; }); - var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var newLine = ts.getNewLineCharacter(compilerOptions, system); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var newLine = updateNewLine(); var compilerHost = { getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: getDefaultLibLocation, - getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, - writeFile: ts.notImplemented, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: fileExists, - readFile: function (fileName) { return system.readFile(fileName); }, - trace: function (s) { return system.write(s + newLine); }, - directoryExists: function (directoryName) { return directoryStructureHost.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return directoryStructureHost.getDirectories(path); }, - realpath: realpath, - resolveTypeReferenceDirectives: function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }, - resolveModuleNames: function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, false); }, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), toPath: toPath, getCompilationSettings: function () { return compilerOptions; }, watchDirectoryOfFailedLookupLocation: watchDirectory, watchTypeRootsDirectory: watchDirectory, - getCachedDirectoryStructureHost: getCachedDirectoryStructureHost, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, onInvalidatedResolution: scheduleProgramUpdate, onChangedAutomaticTypeDirectiveNames: function () { hasChangedAutomaticTypeDirectiveNames = true; scheduleProgramUpdate(); }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, writeLog: writeLog }; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? - ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, getCurrentDirectory())) : - getCurrentDirectory()); - var builder = ts.createBuilder({ getCanonicalFileName: getCanonicalFileName, computeHash: computeHash }); + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, false); + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : + (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : + (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); synchronizeProgram(); watchConfigFileWildCardDirectories(); - return function () { return program; }; + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } function synchronizeProgram() { writeLog("Synchronizing program"); + var program = getCurrentProgram(); if (hasChangedCompilerOptions) { - newLine = ts.getNewLineCharacter(compilerOptions, system); + newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(); - if (ts.isProgramUptoDate(program, rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { - return; + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + return builderProgram; } - beforeCompile(compilerOptions); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - program = ts.createProgram(rootFileNames, compilerOptions, compilerHost, program); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); resolutionCache.finishCachingPerDirectoryResolution(); - builder.updateProgram(program); - ts.updateMissingFilePathsWatch(program, missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -60875,11 +62028,22 @@ var ts; } missingFilePathsRequestedForRelease = undefined; } - afterCompile(directoryStructureHost, program, builder); - reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); + return builderProgram; + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); } function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function fileExists(fileName) { var path = toPath(fileName); @@ -60889,9 +62053,6 @@ var ts; } return directoryStructureHost.fileExists(fileName); } - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { var hostSourceFile = sourceFilesCache.get(path); if (ts.isString(hostSourceFile)) { @@ -60907,7 +62068,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(system, fileName, onSourceFileChange, path, writeLog); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); } } else { @@ -60918,9 +62079,9 @@ var ts; else { var fileWatcher = void 0; if (sourceFile) { - sourceFile.version = "0"; - fileWatcher = watchFilePath(system, fileName, onSourceFileChange, path, writeLog); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: 0, fileWatcher: fileWatcher }); + sourceFile.version = "1"; + fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: 1, fileWatcher: fileWatcher }); } else { sourceFilesCache.set(path, "0"); @@ -60933,7 +62094,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, compilerOptions.charset); + text = host.readFile(fileName, compilerOptions.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -60971,14 +62132,19 @@ var ts; } } } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); + } + } function scheduleProgramUpdate() { - if (!system.setTimeout || !system.clearTimeout) { + if (!host.setTimeout || !host.clearTimeout) { return; } if (timerToUpdateProgram) { - system.clearTimeout(timerToUpdateProgram); + host.clearTimeout(timerToUpdateProgram); } - timerToUpdateProgram = system.setTimeout(updateProgram, 250); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); } function scheduleProgramReload() { ts.Debug.assert(!!configFileName); @@ -60987,20 +62153,21 @@ var ts; } function updateProgram() { timerToUpdateProgram = undefined; - reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation)); + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: return reloadFileNamesFromConfigFile(); case ts.ConfigFileProgramReloadLevel.Full: return reloadConfigFile(); default: - return synchronizeProgram(); + synchronizeProgram(); + return; } } function reloadFileNamesFromConfigFile() { - var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, directoryStructureHost); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { - reportDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); } rootFileNames = result.fileNames; synchronizeProgram(); @@ -61008,16 +62175,20 @@ var ts; function reloadConfigFile() { writeLog("Reloading config file: " + configFileName); reloadLevel = ts.ConfigFileProgramReloadLevel.None; - var cachedHost = directoryStructureHost; - cachedHost.clearCache(); - var configParseResult = parseConfigFile(configFileName, optionsToExtendForConfigFile, cachedHost, reportDiagnostic, reportWatchDiagnostic); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + var configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); rootFileNames = configParseResult.fileNames; compilerOptions = configParseResult.options; - hasChangedCompilerOptions = true; configFileSpecs = configParseResult.configFileSpecs; configFileWildCardDirectories = configParseResult.wildcardDirectories; - synchronizeProgram(); - watchConfigFileWildCardDirectories(); } function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); @@ -61027,7 +62198,7 @@ var ts; resolutionCache.invalidateResolutionOfFile(path); if (!ts.isString(hostSourceFile)) { hostSourceFile.fileWatcher.close(); - sourceFilesCache.set(path, (hostSourceFile.version++).toString()); + sourceFilesCache.set(path, (++hostSourceFile.version).toString()); } } else { @@ -61042,15 +62213,15 @@ var ts; scheduleProgramUpdate(); } function updateCachedSystemWithFile(fileName, path, eventKind) { - if (configFileName) { - directoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); } } function watchDirectory(directory, cb, flags) { - return watchDirectoryWorker(system, directory, cb, flags, writeLog); + return watchDirectoryWorker(host, directory, cb, flags, writeLog); } function watchMissingFilePath(missingFilePath) { - return watchFilePath(system, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -61062,13 +62233,18 @@ var ts; } } function watchConfigFileWildCardDirectories() { - ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + if (configFileWildCardDirectories) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } } function watchWildcardDirectory(directory, flags) { return watchDirectory(directory, function (fileOrDirectory) { ts.Debug.assert(!!configFileName); var fileOrDirectoryPath = toPath(fileOrDirectory); - var result = directoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + var result = cachedDirectoryStructureHost && cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { hostSourceFile.version++; @@ -61086,10 +62262,29 @@ var ts; } }, flags); } - function computeHash(data) { - return system.createHash ? system.createHash(data) : data; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } } } + ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); var ts; (function (ts) { @@ -61224,12 +62419,14 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", + "esnext.promise": "lib.esnext.promise.d.ts", }), }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -61470,6 +62667,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -61750,17 +62954,17 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; function convertEnableAutoDiscoveryToEnable(typeAcquisition) { if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - var result = { + return { enable: typeAcquisition.enableAutoDiscovery, include: typeAcquisition.include || [], exclude: typeAcquisition.exclude || [] }; - return result; } return typeAcquisition; } @@ -62173,7 +63377,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -62197,7 +63401,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } @@ -62570,8 +63774,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - return options; + return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -62652,7 +63855,6 @@ var ts; return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; @@ -62735,9 +63937,6 @@ var ts; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } - else if (invalidMultipleRecursionPatterns.test(spec)) { - return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; - } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } @@ -62871,10 +64070,10 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - var reportDiagnostic = ts.createDiagnosticReporter(ts.sys, ts.reportDiagnosticSimply); + var reportDiagnostic = ts.createDiagnosticReporter(ts.sys); function udpateReportDiagnostic(options) { if (options.pretty) { - reportDiagnostic = ts.createDiagnosticReporter(ts.sys, ts.reportDiagnosticWithColorAndContext); + reportDiagnostic = ts.createDiagnosticReporter(ts.sys, true); } } function padLeft(s, length) { @@ -62896,7 +64095,7 @@ var ts; ts.validateLocaleAndSetLanguage(commandLine.options.locale, ts.sys, commandLine.errors); } if (commandLine.errors.length > 0) { - ts.reportDiagnostics(commandLine.errors, reportDiagnostic); + commandLine.errors.forEach(reportDiagnostic); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.init) { @@ -62944,12 +64143,11 @@ var ts; } var commandLineOptions = commandLine.options; if (configFileName) { - var reportWatchDiagnostic = ts.createWatchDiagnosticReporter(); - var configParseResult = ts.parseConfigFile(configFileName, commandLineOptions, ts.sys, reportDiagnostic, reportWatchDiagnostic); + var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, ts.sys, reportDiagnostic); udpateReportDiagnostic(configParseResult.options); if (ts.isWatchSet(configParseResult.options)) { reportWatchModeWithoutSysSupport(); - ts.createWatchModeWithConfigFile(configParseResult, commandLineOptions, createWatchingSystemHost(reportWatchDiagnostic)); + createWatchOfConfigFile(configParseResult, commandLineOptions); } else { performCompilation(configParseResult.fileNames, configParseResult.options); @@ -62959,7 +64157,7 @@ var ts; udpateReportDiagnostic(commandLineOptions); if (ts.isWatchSet(commandLineOptions)) { reportWatchModeWithoutSysSupport(); - ts.createWatchModeWithoutConfigFile(commandLine.fileNames, commandLineOptions, createWatchingSystemHost()); + createWatchOfFilesAndCompilerOptions(commandLine.fileNames, commandLineOptions); } else { performCompilation(commandLine.fileNames, commandLineOptions); @@ -62977,32 +64175,38 @@ var ts; var compilerHost = ts.createCompilerHost(compilerOptions); enableStatistics(compilerOptions); var program = ts.createProgram(rootFileNames, compilerOptions, compilerHost); - var exitStatus = compileProgram(program); + var exitStatus = ts.emitFilesAndReportErrors(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }); reportStatistics(program); return ts.sys.exit(exitStatus); } - function createWatchingSystemHost(reportWatchDiagnostic) { - var watchingHost = ts.createWatchingSystemHost(undefined, ts.sys, ts.parseConfigFile, reportDiagnostic, reportWatchDiagnostic); - watchingHost.beforeCompile = enableStatistics; - var afterCompile = watchingHost.afterCompile; - watchingHost.afterCompile = function (host, program, builder) { - afterCompile(host, program, builder); - reportStatistics(program); + function updateWatchCompilationHost(watchCompilerHost) { + var compileUsingBuilder = watchCompilerHost.createProgram; + watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram) { + enableStatistics(options); + return compileUsingBuilder(rootNames, options, host, oldProgram); + }; + var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; + watchCompilerHost.afterProgramCreate = function (builderProgram) { + emitFilesUsingBuilder(builderProgram); + reportStatistics(builderProgram.getProgram()); }; - return watchingHost; } - function compileProgram(program) { - var diagnostics; - diagnostics = program.getSyntacticDiagnostics().slice(); - if (diagnostics.length === 0) { - diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { - diagnostics = program.getSemanticDiagnostics().slice(); - } - } - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; - ts.addRange(diagnostics, emitDiagnostics); - return ts.handleEmitOutputAndReportErrors(ts.sys, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic); + function createWatchStatusReporter(options) { + return ts.createWatchStatusReporter(ts.sys, !!options.pretty); + } + function createWatchOfConfigFile(configParseResult, optionsToExtend) { + var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, ts.sys, undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); + updateWatchCompilationHost(watchCompilerHost); + watchCompilerHost.rootFiles = configParseResult.fileNames; + watchCompilerHost.options = configParseResult.options; + watchCompilerHost.configFileSpecs = configParseResult.configFileSpecs; + watchCompilerHost.configFileWildCardDirectories = configParseResult.wildcardDirectories; + ts.createWatchProgram(watchCompilerHost); + } + function createWatchOfFilesAndCompilerOptions(rootFiles, options) { + var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, ts.sys, undefined, reportDiagnostic, createWatchStatusReporter(options)); + updateWatchCompilationHost(watchCompilerHost); + ts.createWatchProgram(watchCompilerHost); } function enableStatistics(compilerOptions) { if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 30fde91af76cf..7128578348749 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -437,14 +437,17 @@ var ts; RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); var TokenFlags; (function (TokenFlags) { TokenFlags[TokenFlags["None"] = 0] = "None"; @@ -457,8 +460,9 @@ var ts; TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; - TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { @@ -496,49 +500,71 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); var SymbolAccessibility; (function (SymbolAccessibility) { @@ -654,6 +680,7 @@ var ts; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -765,6 +792,7 @@ var ts; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); var Variance; @@ -787,11 +815,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1051,6 +1077,8 @@ var ts; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; @@ -1060,20 +1088,22 @@ var ts; TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -1108,6 +1138,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1144,6 +1175,72 @@ var ts; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -1205,7 +1302,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1214,6 +1311,7 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -1339,6 +1437,9 @@ var ts; } ts.forEach = forEach; function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -1348,6 +1449,19 @@ var ts; return undefined; } ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1364,13 +1478,27 @@ var ts; ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { var result = []; - Debug.assert(arrayA.length === arrayB.length); + Debug.assertEqual(arrayA.length, arrayB.length); for (var i = 0; i < arrayA.length; i++) { result.push(callback(arrayA[i], arrayB[i], i)); } return result; } ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; function zipToMap(keys, values) { Debug.assert(keys.length === values.length); var map = createMap(); @@ -1443,17 +1571,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -1525,11 +1642,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1590,25 +1708,33 @@ var ts; return result; } ts.flatMap = flatMap; - function flatMapIter(iter, mapfn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapfn(value); - if (res) { - if (isArray(res)) { - result.push.apply(result, res); - } - else { - result.push(res); + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); } - } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; } - return result; } - ts.flatMapIter = flatMapIter; + ts.flatMapIterator = flatMapIterator; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1631,12 +1757,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -1645,20 +1782,35 @@ var ts; return result; } ts.mapDefined = mapDefined; - function mapDefinedIter(iter, mapFn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapFn(value); - if (res !== undefined) { - result.push(res); + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } } - } - return result; + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; } - ts.mapDefinedIter = mapDefinedIter; + ts.singleIterator = singleIterator; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -2298,6 +2450,8 @@ var ts; ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; function notImplemented() { throw new Error("Not implemented"); } @@ -2625,7 +2779,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47) + if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) return 3; } if (path.lastIndexOf("file:///", 0) === 0) { @@ -2692,10 +2846,6 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function moduleHasNonRelativeName(moduleName) { - return !ts.isExternalModuleNameRelative(moduleName); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2718,7 +2868,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3001,7 +3153,6 @@ var ts; function getSubPatternFromSpec(spec, basePath, usage, _a) { var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; - var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); var lastComponent = lastOrUndefined(components); @@ -3016,11 +3167,7 @@ var ts; for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { var component = components_1[_i]; if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - return undefined; - } subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; } else { if (usage === "directories") { @@ -3295,10 +3442,10 @@ var ts; } function Signature() { } function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0; this.modifierFlagsCache = 0; this.transformFlags = 0; @@ -3432,9 +3579,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; function matchPatternOrExact(patternStrings, candidate) { @@ -3531,170 +3676,20 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - clearCache(); - } - else { - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - clearCache(); - } - else { - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.singleElementArray = singleElementArray; })(ts || (ts = {})); var ts; (function (ts) { @@ -3931,7 +3926,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -3964,6 +3959,9 @@ var ts; return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } var nodeSystem = { + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -4042,7 +4040,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -4368,6 +4371,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4482,6 +4487,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -4536,7 +4542,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -4624,6 +4630,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4702,6 +4709,10 @@ var ts; Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4788,7 +4799,6 @@ var ts; The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), @@ -4839,6 +4849,7 @@ var ts; Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), @@ -4879,7 +4890,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -4986,6 +4997,9 @@ var ts; Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5014,6 +5028,9 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5089,9 +5106,9 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -5103,6 +5120,9 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); var ts; @@ -5134,9 +5154,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -5569,8 +5589,8 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { @@ -5587,10 +5607,16 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - if (!compilerOptions.preserveSymlinks) { - resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + var originalPath = void 0; + if (!compilerOptions.preserveSymlinks && resolvedValue) { + originalPath = resolvedValue.path; + var path = realPath(resolved_1.value.path, host, traceEnabled); + if (path === originalPath) { + originalPath = undefined; + } + resolvedValue = __assign({}, resolvedValue, { path: path }); } - return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -5625,7 +5651,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -5639,6 +5667,38 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts"; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } @@ -5712,18 +5772,41 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { - var host = _a.host, traceEnabled = _a.traceEnabled; + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); + if (subModuleName === "") { + var path = tryReadPackageJsonFields(true, packageJsonContent, nodeModuleDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + } + else { + var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); + if (typeof jsPath === "string") { + subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js"), ".jsx") + ".d.ts"; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts")) { + subModuleName = addExtensionAndIndex(subModuleName); + } var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -5866,13 +5949,17 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -5888,7 +5975,7 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, undefined, false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { @@ -5926,7 +6013,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, undefined, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; function toSearchResult(value) { @@ -5935,8 +6022,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.emptyArray = []; + ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -5956,15 +6044,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return str += " "; }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -5976,10 +6073,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -6013,12 +6110,19 @@ var ts; return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -6189,7 +6293,7 @@ var ts; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { - if (!nodeIsSynthesized(node) && node.parent) { + if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; @@ -6587,7 +6691,7 @@ var ts; return node === parent.type; case 182: case 183: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184: return false; } @@ -7263,41 +7367,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 && node.body && node.body.kind === 234 && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -7321,7 +7414,7 @@ var ts; if (node.kind === 147) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -7426,6 +7519,29 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208: + case 209: + case 221: + case 212: + case 222: + case 236: + case 261: + case 262: + case 223: + case 215: + case 216: + case 217: + case 213: + case 214: + case 225: + case 264: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -7746,6 +7862,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; function isESSymbolIdentifier(node) { return node.kind === 71 && node.escapedText === "Symbol"; } @@ -8162,7 +8282,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -8338,7 +8470,7 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (node.type) { + if (ts.hasType(node)) { return node.type; } if (checkJSDoc || isInJavaScriptFile(node)) { @@ -8712,14 +8844,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -9021,6 +9153,10 @@ var ts; return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9694,7 +9830,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192; + return node.kind === 190; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -10138,7 +10274,7 @@ var ts; } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { - return ts.isIdentifier(node) && node.autoGenerateKind > 0; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; } ts.isGeneratedIdentifier = isGeneratedIdentifier; function isModifierKind(token) { @@ -10245,6 +10381,17 @@ var ts; return node && (node.kind === 154 || node.kind === 155); } ts.isAccessor = isAccessor; + function isMethodOrAccessor(node) { + switch (node.kind) { + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; function isTypeElement(node) { var kind = node.kind; return kind === 157 @@ -10726,6 +10873,33 @@ var ts; return !!node.jsDoc && node.jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257: + case 259: + case 265: + case 266: + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); var ts; (function (ts) { @@ -11132,7 +11306,7 @@ var ts; } function scanConflictMarkerTrivia(text, pos, error) { if (error) { - error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); } var ch = text.charCodeAt(pos); var len = text.length; @@ -11356,19 +11530,60 @@ var ts; lookAhead: lookAhead, scanRange: scanRange, }; - function error(message, length) { + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } if (onError) { + var oldPos = pos; + pos = errPos; onError(message, length || 0); + pos = oldPos; } } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } function scanNumber() { var start = pos; - while (isDigit(text.charCodeAt(pos))) - pos++; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; if (text.charCodeAt(pos) === 46) { pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; + decimalFragment = scanNumberFragment(); } var end = pos; if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { @@ -11376,17 +11591,29 @@ var ts; tokenFlags |= 16; if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++; - if (isDigit(text.charCodeAt(pos))) { - pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; - end = pos; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); } else { - error(ts.Diagnostics.Digit_expected); + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; } } - return "" + +(text.substring(start, end)); + if (tokenFlags & 512) { + var result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + return "" + +result; + } + else { + return "" + +(text.substring(start, end)); + } } function scanOctalDigits() { var start = pos; @@ -11395,17 +11622,35 @@ var ts; } return +(text.substring(start, pos)); } - function scanExactNumberOfHexDigits(count) { - return scanHexDigits(count, false); + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(count, false, canHaveSeparators); } - function scanMinimumNumberOfHexDigits(count) { - return scanHexDigits(count, true); + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(count, true, canHaveSeparators); } - function scanHexDigits(minCount, scanAsManyAsPossible) { + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { var digits = 0; var value = 0; + var allowSeparator = false; + var isPreviousTokenSeparator = false; while (digits < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; if (ch >= 48 && ch <= 57) { value = value * 16 + ch - 48; } @@ -11420,10 +11665,14 @@ var ts; } pos++; digits++; + isPreviousTokenSeparator = false; } if (digits < minCount) { value = -1; } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return value; } function scanString(jsxAttributeString) { @@ -11559,7 +11808,7 @@ var ts; } } function scanHexadecimalEscape(numDigits) { - var escapedValue = scanExactNumberOfHexDigits(numDigits); + var escapedValue = scanExactNumberOfHexDigits(numDigits, false); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); } @@ -11569,7 +11818,7 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1); + var escapedValue = scanMinimumNumberOfHexDigits(1, false); var isInvalidExtendedEscape = false; if (escapedValue < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); @@ -11608,7 +11857,7 @@ var ts; if (pos + 5 < end && text.charCodeAt(pos + 1) === 117) { var start_1 = pos; pos += 2; - var value = scanExactNumberOfHexDigits(4); + var value = scanExactNumberOfHexDigits(4, false); pos = start_1; return value; } @@ -11656,8 +11905,26 @@ var ts; ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; + var separatorAllowed = false; + var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; var valueOfCh = ch - 48; if (!isDigit(ch) || valueOfCh >= base) { break; @@ -11665,10 +11932,15 @@ var ts; value = value * base + valueOfCh; pos++; numberOfDigits++; + isPreviousTokenSeparator = false; } if (numberOfDigits === 0) { return -1; } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + return value; + } return value; } function scan() { @@ -11854,7 +12126,7 @@ var ts; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1); + var value = scanMinimumNumberOfHexDigits(1, true); if (value < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -12175,7 +12447,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -12197,6 +12469,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9: case 11: @@ -12207,55 +12480,30 @@ var ts; } return token = 5; case 64: - pos++; return token = 57; case 10: case 13: - pos++; return token = 4; case 42: - pos++; return token = 39; case 123: - pos++; return token = 17; case 125: - pos++; return token = 18; case 91: - pos++; return token = 21; case 93: - pos++; return token = 22; case 60: - pos++; return token = 27; - case 62: - pos++; - return token = 29; case 61: - pos++; return token = 58; case 44: - pos++; return token = 26; case 46: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24; - } return token = 23; - case 33: - pos++; - return token = 51; - case 63: - pos++; - return token = 55; } if (isIdentifierStart(ch, 6)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } @@ -12263,7 +12511,7 @@ var ts; return token = 71; } else { - return pos += 1, token = 0; + return token = 0; } } function speculationHelper(callback, isLookahead) { @@ -12409,20 +12657,48 @@ var ts; case 267: return visitNode(cbNode, node.expression); case 147: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 150: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 149: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 265: - case 227: - case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 227: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); + case 177: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 161: case 162: case 156: @@ -12938,15 +13214,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -13382,9 +13650,12 @@ var ts; return token() === 26 || token() === 24 || isIdentifierOrPattern(); case 18: return isIdentifier(); - case 11: case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); + if (token() === 26) { + return true; + } + case 11: + return token() === 24 || isStartOfExpression(); case 16: return isStartOfParameter(); case 19: @@ -13544,6 +13815,9 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -13844,7 +14118,7 @@ var ts; node.isUnterminated = true; } if (node.kind === 8) { - node.numericLiteralFlags = scanner.getTokenFlags() & 496; + node.numericLiteralFlags = scanner.getTokenFlags() & 1008; } nextToken(); finishNode(node); @@ -14787,7 +15061,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -16226,6 +16502,7 @@ var ts; switch (token()) { case 19: case 27: + case 51: case 56: case 58: case 55: @@ -16826,7 +17103,6 @@ var ts; return result; } scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; var state = 1; var margin = undefined; var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; @@ -16837,23 +17113,22 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5) { + t = nextJSDocToken(); } - if (token() === 4) { + if (t === 4) { state = 0; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1) { - switch (token()) { + loop: while (true) { + switch (t) { case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); parseTag(indent); state = 0; - advanceToken = false; margin = undefined; indent++; } @@ -16892,18 +17167,13 @@ var ts; indent += whitespace.length; break; case 1: - break; + break loop; default: state = 2; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -16987,7 +17257,8 @@ var ts; if (!tag) { return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -17000,8 +17271,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 && token() !== 1) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4: if (state >= 1) { state = 0; @@ -17010,7 +17282,9 @@ var ts; indent = 0; break; case 57: - break; + scanner.setTextPos(scanner.getTextPos() - 1); + case 1: + break loop; case 5: if (state === 2) { pushComment(scanner.getTokenText()); @@ -17026,7 +17300,7 @@ var ts; case 39: if (state === 0) { state = 1; - indent += scanner.getTokenText().length; + indent += 1; break; } default: @@ -17034,14 +17308,11 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57) { - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281, atToken.pos); @@ -17049,8 +17320,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -17119,10 +17389,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280, start_2); @@ -17226,10 +17493,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -17274,8 +17538,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57: if (canParseTag) { var child = tryParseChildTag(target); @@ -17315,33 +17578,43 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0; + break; case "arg": case "argument": case "param": - return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -17360,6 +17633,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -17914,7 +18195,7 @@ var ts; case 147: ts.Debug.assert(node.parent.kind === 277); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -18248,7 +18529,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 || expr2.kind === 13); + } + function isNarrowableInOperands(left, right) { + return (left.kind === 9 || left.kind === 13) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -18262,6 +18546,8 @@ var ts; isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 93: return isNarrowableOperand(expr.left); + case 92: + return isNarrowableInOperands(expr.left, expr.right); case 26: return isNarrowingExpression(expr.right); } @@ -19464,23 +19750,9 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { setCommonJsModuleIndicator(node); return; } @@ -19534,7 +19806,7 @@ var ts; if (node.kind === 195) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { bindExportsPropertyAssignment(node); } else { @@ -19543,11 +19815,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -19638,7 +19906,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1, 107455); @@ -19715,6 +19983,28 @@ var ts; return true; } } + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } function computeTransformFlagsForNode(node, subtreeFlags) { var kind = node.kind; switch (kind) { @@ -19769,6 +20059,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180: return computePropertyAccess(node, subtreeFlags); + case 181: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -19777,13 +20069,15 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3; } if (subtreeFlags & 524288 - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 | 268435456))) { transformFlags |= 192; + if (expression.transformFlags & 268435456) { + transformFlags |= 16384; + } } if (expression.kind === 91) { transformFlags |= 67108864; @@ -19792,19 +20086,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97: - return true; - case 180: - case 181: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97; - } - return false; + return transformFlags & ~940049729; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19815,7 +20097,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; + return transformFlags & ~940049729; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19832,7 +20114,7 @@ var ts; transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19855,7 +20137,7 @@ var ts; transformFlags |= 192 | 131072; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19888,7 +20170,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -19900,7 +20182,7 @@ var ts; transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19916,7 +20198,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19927,7 +20209,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; + return transformFlags & ~940574017; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -19935,7 +20217,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19947,7 +20229,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -19969,7 +20251,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -19984,7 +20266,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; @@ -19992,7 +20274,7 @@ var ts; transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -20022,7 +20304,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20044,7 +20326,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -20063,17 +20345,27 @@ var ts; transformFlags |= 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; + return transformFlags & ~1003902273; } function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (transformFlags & 134217728) { + transformFlags ^= 134217728; + transformFlags |= 268435456; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~671089985; + } + function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; + var expressionFlags = expression.transformFlags; + if (expressionFlags & 134217728) { + transformFlags &= ~134217728; + transformFlags |= 268435456; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~671089985; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20085,7 +20377,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -20100,7 +20392,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20109,7 +20401,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20117,7 +20409,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20125,7 +20417,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -20134,7 +20426,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; + return transformFlags & ~977327425; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432; @@ -20145,16 +20437,22 @@ var ts; transformFlags |= 192 | 4194304; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; + return transformFlags & ~948962625; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 536872257; + var excludeFlags = 939525441; switch (kind) { case 120: case 192: transformFlags |= 8 | 16; break; + case 185: + case 203: + case 292: + transformFlags |= 3; + excludeFlags = 536872257; + break; case 114: case 112: case 113: @@ -20163,8 +20461,6 @@ var ts; case 76: case 233: case 268: - case 185: - case 203: case 204: case 131: transformFlags |= 3; @@ -20262,7 +20558,8 @@ var ts; transformFlags |= 8 | 1048576; break; case 97: - transformFlags |= 192; + transformFlags |= 192 | 134217728; + excludeFlags = 536872257; break; case 99: transformFlags |= 16384; @@ -20272,11 +20569,11 @@ var ts; if (subtreeFlags & 524288) { transformFlags |= 8 | 1048576; } - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 176: transformFlags |= 192 | 8388608; - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 177: transformFlags |= 192; @@ -20288,7 +20585,7 @@ var ts; transformFlags |= 3 | 4096; break; case 179: - excludeFlags = 540087617; + excludeFlags = 942740801; if (subtreeFlags & 2097152) { transformFlags |= 192; } @@ -20301,7 +20598,7 @@ var ts; break; case 178: case 183: - excludeFlags = 537396545; + excludeFlags = 940049729; if (subtreeFlags & 524288) { transformFlags |= 192; } @@ -20336,27 +20633,27 @@ var ts; case 182: case 183: case 178: - return 537396545; + return 940049729; case 234: - return 574674241; + return 977327425; case 147: - return 536872257; + return 939525441; case 188: - return 601249089; + return 1003902273; case 187: case 229: - return 601281857; + return 1003935041; case 228: - return 546309441; + return 948962625; case 230: case 200: - return 539358529; + return 942011713; case 153: - return 601015617; + return 1003668801; case 152: case 154: case 155: - return 601015617; + return 1003668801; case 119: case 133: case 130: @@ -20375,14 +20672,23 @@ var ts; case 232: return -3; case 179: - return 540087617; + return 942740801; case 264: - return 537920833; + return 940574017; case 175: case 176: - return 537396545; - default: + return 940049729; + case 185: + case 203: + case 292: + case 186: + case 97: return 536872257; + case 180: + case 181: + return 671089985; + default: + return 939525441; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -20393,7 +20699,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -20486,8 +20792,9 @@ var ts; visitType(type.modifiersType); } function visitSignature(signature) { - if (signature.typePredicate) { - visitType(signature.typePredicate.type); + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); } ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { @@ -20649,6 +20956,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -20682,16 +20994,32 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { node = ts.getParseTreeNode(node, ts.isExpression); return node ? getContextualType(node) : undefined; }, + isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { node = ts.getParseTreeNode(node, ts.isCallLikeExpression); @@ -20706,7 +21034,11 @@ var ts; }, isValidPropertyAccess: function (node, propertyName) { node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (node, type, property) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); }, getSignatureFromDeclaration: function (declaration) { declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); @@ -20730,7 +21062,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -20770,11 +21102,17 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -20818,6 +21156,7 @@ var ts; var markerSubType = createType(32768); markerSubType.constraint = markerSuperType; var markerOtherType = createType(32768); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); @@ -20825,6 +21164,7 @@ var ts; var enumNumberIndexInfo = createIndexInfo(stringType, true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); var globals = ts.createSymbolTable(); + var reverseMappedCache = ts.createMap(); var ambientModulesCache; var patternAmbientModules; var globalObjectType; @@ -20979,19 +21319,20 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - var _displayBuilder; var TypeSystemPropertyName; (function (TypeSystemPropertyName) { TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { CheckMode[CheckMode["Normal"] = 0] = "Normal"; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; })(CheckMode || (CheckMode = {})); var CallbackCheck; (function (CallbackCheck) { @@ -21021,6 +21362,139 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 | 8192, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 | 3112960 | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -21036,8 +21510,10 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { - getDiagnostics(sourceFile, cancellationToken); + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -21272,7 +21748,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { if (declaration.kind === 177) { @@ -21336,10 +21812,11 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; var result; var lastLocation; @@ -21493,7 +21970,7 @@ var ts; } break; } - if (location.kind !== 208) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; @@ -21509,7 +21986,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -21557,6 +22036,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208: + case 235: + case 222: + case 236: + case 261: + case 262: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -21712,6 +22205,30 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export="); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + if (!file || file.isDeclarationFile) { + if (resolveExportByName(moduleSymbol, "default", dontResolveAlias)) { + return false; + } + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + return false; + } + return true; + } + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -21720,15 +22237,14 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -22006,7 +22522,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -22034,8 +22550,41 @@ var ts; } function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 | 3))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -22257,11 +22806,11 @@ var ts; } var visitedSymbolTables = []; return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols); + var result = trySymbolTable(symbols, ignoreQualification); visitedSymbolTables.pop(); return result; } @@ -22269,16 +22818,16 @@ var ts; return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function isUMDExportSymbol(symbol) { return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.escapedName))) { + function trySymbolTable(symbols, ignoreQualification) { + if (isAccessible(symbols.get(symbol.escapedName), undefined, ignoreQualification)) { return [symbol]; } return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { @@ -22287,10 +22836,11 @@ var ts; && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, true); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -22339,6 +22889,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); return access.accessibility === 0; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455, false); + return access.accessibility === 0; + } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; @@ -22429,97 +22983,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4; } + var nodeFlags = 3112960; + if (flags & 2) { + nodeFlags |= 128; + } + if (flags & 1) { + nodeFlags |= 512; + } + var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, entity, sourceFile, writer); + return writer; + } } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144) { + sigOutput = kind === 1 ? 162 : 161; + } + else { + sigOutput = kind === 1 ? 157 : 156; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, sig, sourceFile, writer); + return writer; + } } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608; + context.flags &= ~8388608; if (!type) { context.encounteredError = true; return undefined; @@ -22556,6 +23144,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024) { + if (!(context.flags & 1048576)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140, ts.createKeywordTypeNode(137)); } if (type.flags & 2048) { @@ -22577,10 +23170,13 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 32768 && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304) { + if (!context.encounteredError && !(context.flags & 32768)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -22593,7 +23189,7 @@ var ts; var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } - if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -22606,7 +23202,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144)) { context.encounteredError = true; } return undefined; @@ -22631,7 +23227,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1); @@ -22639,7 +23235,7 @@ var ts; function createAnonymousTypeNode(type) { var symbol = type.symbol; if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455); @@ -22658,10 +23254,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; + if (isConstructorObject) { + return createTypeNodeFromObjectType(type); + } + else { + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } } } else { @@ -22676,7 +23278,8 @@ var ts; return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); + return (!!(context.flags & 4096) || ts.contains(context.symbolStack, symbol)) && + (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } } @@ -22701,11 +23304,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, false); @@ -22718,7 +23321,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -22732,12 +23335,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -22813,7 +23421,10 @@ var ts; typeElements.push(signatureToSignatureDeclarationHelper(signature, 157, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); + var indexInfo = resolvedType.objectFlags & 2048 ? + createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : + resolvedType.stringIndexInfo; + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0, context)); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); @@ -22824,9 +23435,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); + if (context.flags & 2048) { + if (propertySymbol.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 | 16) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455); + } + } var propertyName = symbolToName(propertySymbol, context, 107455, true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; @@ -22867,19 +23493,29 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152)) { + context.encounteredError = true; + } return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); } var returnTypeNode; - if (signature.typePredicate) { - var typePredicate = signature.typePredicate; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { var parameterName = typePredicate.kind === 1 ? ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216) : ts.createThisTypeNode(); @@ -22890,7 +23526,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256) { if (returnTypeNode && returnTypeNode.kind === 119) { returnTypeNode = undefined; } @@ -22898,14 +23534,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var savedContextFlags = context.flags; + context.flags &= ~512; var name = symbolToName(type.symbol, context, 793064, true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -22916,7 +23555,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -22940,45 +23579,20 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -23001,11 +23615,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, predicate, sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -23061,6 +23757,9 @@ var ts; return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 && symbol.escapedName === "default") { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -23070,7 +23769,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072)) { context.encounteredError = true; } switch (declaration.kind) { @@ -23089,668 +23788,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91) { - writePunctuation(writer, 21); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91) { - writePunctuation(writer, 22); - } - } - else { - writePunctuation(writer, 23); - writer.writeSymbol(symbolName, symbol); - } - } - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 256 & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 | 16384); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024; - if (type.flags & 33585807) { - writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 && !(type.flags & 131072)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 || type.flags & (272 | 32768)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 1024) && type.aliasSymbol && - ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 | 32)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024) { - if (flags & 131072) { - writeKeyword(writer, 140); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137); - } - else if (type.flags & 96) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128); - if (flags & 128) { - writePunctuation(writer, 20); - } - } - else if (type.flags & 1048576) { - writeType(type.objectType, 128); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 17); - writeSpace(writer); - writePunctuation(writer, 24); - writeSpace(writer); - writePunctuation(writer, 18); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 ? 0 : 128); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); - } - if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 512); - pos++; - while (pos < end) { - writePunctuation(writer, 26); - writeSpace(writer); - writeType(typeArguments[pos], 0); - pos++; - } - writePunctuation(writer, 29); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 128 | 32768); - writePunctuation(writer, 21); - writePunctuation(writer, 22); - } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); - } - else if (flags & 16384 && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200) { - writeAnonymousType(type, flags); - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128) { - writePunctuation(writer, 19); - } - if (type.flags & 131072) { - writeTypeList(formatUnionTypes(type.types), 49); - } - else { - writeTypeList(type.types, 48); - } - if (flags & 128) { - writePunctuation(writer, 20); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - if (symbol.flags & 32 && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 && flags & 16384) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); - } - else { - writeKeyword(writer, 119); - } - } - else { - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192) && - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 || declaration.parent.kind === 235; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 4) || - ts.contains(symbolStack, symbol); - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 103); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - if (typeFormatFlags & 32768) { - writePunctuation(writer, 20); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216) { - writePunctuation(writer, 55); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128) { - return true; - } - else if (flags & 512) { - var typeParameters = callSignature.target && (flags & 64) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 94); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (flags & 128) { - writePunctuation(writer, 20); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384) { - if (p.flags & 4194304) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56); - writeSpace(writer); - writeType(t, globalFlags & 16384); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); - if (type.declaration.questionToken) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 175) { - writePunctuation(writer, 17); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); - } - else if (bindingPattern.kind === 176) { - writePunctuation(writer, 21); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); - } - writePunctuation(writer, 22); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 512; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - flags = 0; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99); - } - writeSpace(writer); - writeKeyword(writer, 126); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 && isTypeAny(returnType)) { - return; - } - if (flags & 16) { - writeSpace(writer); - writePunctuation(writer, 36); - } - else { - writePunctuation(writer, 56); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); - writeSpace(writer); - } - if (signature.target && (flags & 64)) { - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); - writeSpace(writer); - switch (kind) { - case 1: - writeKeyword(writer, 133); - break; - case 0: - writeKeyword(writer, 136); - break; - } - writePunctuation(writer, 22); - writePunctuation(writer, 56); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -23862,8 +23899,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -23897,6 +23934,10 @@ var ts; if (propertyName === 3) { return target.resolvedReturnType; } + if (propertyName === 4) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } function popTypeResolution() { @@ -24002,7 +24043,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); @@ -24018,7 +24060,7 @@ var ts; type = createArrayType(elementType); } else { - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -24037,7 +24079,7 @@ var ts; type = getTypeWithFacts(type, 131072); } return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + getUnionType([type, checkExpressionCached(declaration.initializer)], 2) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -24060,21 +24102,21 @@ var ts; return strictNullChecks && optional ? getOptionalType(type) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.parent.parent.kind === 216) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 216) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); return indexType.flags & (32768 | 524288) ? indexType : stringType; } - if (declaration.parent.parent.kind === 217) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 217) { var forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; } if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, !!declaration.questionToken && includeOptionality); + var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && declaration.kind === 227 && !ts.isBindingPattern(declaration.name) && @@ -24108,19 +24150,16 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } } if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } if (ts.isJsxAttribute(declaration)) { return trueType; } - if (declaration.kind === 266) { - return checkIdentifier(declaration.name); - } if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, false, true); } @@ -24163,7 +24202,7 @@ var ts; types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } } - var type = jsDocType || getUnionType(types, true); + var type = jsDocType || getUnionType(types, 2); return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { @@ -24233,15 +24272,12 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - if (type.flags & 1024 && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 1024 && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } - if (declaration.kind === 265) { - return type; - } return getWidenedType(type); } - type = declaration.dotDotDotToken ? anyArrayType : anyType; + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && noImplicitAny) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { reportImplicitAnyError(declaration, type); @@ -24254,6 +24290,12 @@ var ts; var memberDeclaration = root.kind === 147 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { @@ -24278,9 +24320,38 @@ var ts; declaration.kind === 180 && declaration.parent.kind === 195) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else { + else if (ts.isJSDocPropertyTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } + else { + ts.Debug.fail("Unhandled declaration kind! " + ts.SyntaxKind[declaration.kind]); + } if (!popTypeResolution()) { type = reportCircularityError(symbol); } @@ -24437,6 +24508,9 @@ var ts; if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } + if (ts.getCheckFlags(symbol) & 2048) { + return getTypeOfReverseMappedSymbol(symbol); + } if (symbol.flags & (3 | 4)) { return getTypeOfVariableOrParameterOrProperty(symbol); } @@ -24628,10 +24702,10 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = ts.emptyArray; + type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (65536 | 262144 | 1))) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); @@ -24648,22 +24722,25 @@ var ts; var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; + return type.resolvedBaseTypes = ts.emptyArray; } baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === unknownType) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - return; + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + type.members = undefined; } - type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; @@ -24697,7 +24774,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); } } else { @@ -24845,7 +24922,7 @@ var ts; } } if (memberTypeList.length) { - var enumType_1 = getUnionType(memberTypeList, false, symbol, undefined); + var enumType_1 = getUnionType(memberTypeList, 1, symbol, undefined); if (enumType_1.flags & 131072) { enumType_1.flags |= 256; enumType_1.symbol = symbol; @@ -24933,7 +25010,7 @@ var ts; } function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isThislessType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); } function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); @@ -25101,18 +25178,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -25142,6 +25220,7 @@ var ts; if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); var thisArgument = ts.lastOrUndefined(typeArguments); for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { var baseType = baseTypes_1[_i]; @@ -25169,21 +25248,21 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; + sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -25200,7 +25279,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -25250,12 +25329,13 @@ var ts; if (unionSignatures) { var s = signature; if (unionSignatures.length > 1) { - s = cloneSignature(signature); + var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); } - s.resolvedReturnType = undefined; + s = cloneSignature(signature); + s.thisParameter = thisParameter; s.unionSignatures = unionSignatures; } (result || (result = [])).push(s); @@ -25277,7 +25357,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, 2), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); @@ -25360,6 +25440,7 @@ var ts; if (symbol.exports) { members = getExportsOfSymbol(symbol); } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -25386,6 +25467,23 @@ var ts; } } } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0); + var readonlyMask = type.mappedType.declaration.readonlyToken ? false : true; + var optionalMask = type.mappedType.declaration.questionToken ? 0 : 16777216; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 | (readonlyMask && isReadonlySymbol(prop) ? 8 : 0); + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); var stringIndexInfo; @@ -25494,6 +25592,9 @@ var ts; else if (type.objectFlags & 3) { resolveClassOrInterfaceMembers(type); } + else if (type.objectFlags & 2048) { + resolveReverseMappedTypeMembers(type); + } else if (type.objectFlags & 16) { resolveAnonymousTypeMembers(type); } @@ -25579,12 +25680,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0)) { + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -25603,29 +25707,30 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216) { var types = t.types; @@ -25645,7 +25750,7 @@ var ts; return stringType; } if (t.flags & 1048576) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -25661,7 +25766,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -25705,14 +25810,13 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; - var types = containingType.types; var isUnion = containingType.flags & 131072; var excludeModifiers = isUnion ? 24 : 0; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var current = types_5[_i]; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -25743,8 +25847,8 @@ var ts; var propTypes = []; var declarations = []; var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -25835,7 +25939,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, true); + return getUnionType(propTypes, 2); } } return undefined; @@ -25890,7 +25994,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -25898,27 +26002,26 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 71) { - return { - kind: 1, - parameterName: parameterName ? parameterName.escapedText : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; + return createIdentifierTypePredicate(parameterName && parameterName.escapedText, parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); } else { - return { - kind: 0, - type: getTypeFromTypeNode(node.type) - }; + return createThisTypePredicate(type); } } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0, type: type }; + } function getMinTypeArgumentCount(typeParameters) { var minTypeArgumentCount = 0; if (typeParameters) { @@ -26004,18 +26107,15 @@ var ts; : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 159 ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } function maybeAddJsSyntheticRestParameter(declaration, parameters) { var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -26124,6 +26224,28 @@ var ts; return getTypeOfSymbol(signature.thisParameter); } } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var declaration = signature.declaration; + signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 159 ? + createTypePredicateFromTypePredicateNode(declaration.type) : + noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3)) { @@ -26134,7 +26256,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2); } else { type = getReturnTypeFromBody(signature.declaration); @@ -26270,12 +26392,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -26292,8 +26414,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -26340,7 +26462,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, undefined, 1); + var typeStr = typeToString(type, undefined, 2); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { return unknownType; @@ -26736,14 +26858,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -26801,7 +26923,8 @@ var ts; } } } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1; } if (types.length === 0) { return neverType; } @@ -26813,11 +26936,15 @@ var ts; if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsLiteralOrUniqueESSymbol) { - removeRedundantLiteralTypes(typeSet); + switch (unionReduction) { + case 1: + if (typeSet.containsLiteralOrUniqueESSymbol) { + removeRedundantLiteralTypes(typeSet); + } + break; + case 2: + removeSubtypes(typeSet); + break; } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : @@ -26826,6 +26953,38 @@ var ts; } return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; @@ -26848,7 +27007,7 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } @@ -26879,8 +27038,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } @@ -26905,7 +27064,7 @@ var ts; var unionIndex = typeSet.unionIndex; if (unionIndex !== undefined) { var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), 1, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); @@ -26934,7 +27093,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -26983,6 +27142,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -27054,33 +27214,51 @@ var ts; } return false; } - function getTransformedIndexedAccessType(type) { + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 && getTemplateTypeFromMappedType(type) === neverType; + } + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - if (objectType.flags & 262144 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); + if (objectType.flags & 262144 && isGenericObjectType(objectType)) { + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + if (ts.some(objectType.types, isMappedTypeToNever)) { + var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); + return getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { @@ -27169,10 +27347,7 @@ var ts; if (right.flags & 131072) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 33554432) { - return nonPrimitiveType; - } - if (right.flags & (136 | 84 | 524322 | 272)) { + if (right.flags & (136 | 84 | 524322 | 272 | 33554432)) { return left; } var members = ts.createSymbolTable(); @@ -27223,8 +27398,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= propagatedFlags; - spread.flags |= 2097152 | 8388608; + spread.flags |= propagatedFlags | 8388608; spread.objectFlags |= (128 | 1024); return spread; } @@ -27434,7 +27608,7 @@ var ts; return createTypeMapper(sources, undefined); } function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -27456,7 +27630,7 @@ var ts; result.target = typeParameter; return result; } - function cloneTypePredicate(predicate, mapper) { + function instantiateTypePredicate(predicate, mapper) { if (ts.isIdentifierTypePredicate(predicate)) { return { kind: 1, @@ -27474,7 +27648,6 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); @@ -27483,10 +27656,7 @@ var ts; tp.mapper = mapper; } } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -27611,7 +27781,7 @@ var ts; } } if (type.flags & 131072 && !(type.flags & 16382)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return getUnionType(instantiateTypes(type.types, mapper), 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (type.flags & 262144) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); @@ -27770,7 +27940,7 @@ var ts; var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288) === (getFalsyFlags(targetType) & 12288); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 : 1, false, reportErrors, errorReporter, compareTypes) : @@ -27789,11 +27959,13 @@ var ts; return result; } var sourceReturnType = getReturnTypeOfSignature(source); - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); } @@ -27901,7 +28073,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 64)); } enumRelation.set(id, false); return false; @@ -27983,6 +28155,9 @@ var ts; } return false; } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return source.flags & 67108864 && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var maybeKeys; @@ -28000,10 +28175,22 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, undefined); + if (helpfulRetry) { + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -28013,8 +28200,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 256); - targetType = typeToString(target, undefined, 256); + sourceType = typeToString(source, undefined, 64); + targetType = typeToString(target, undefined, 64); } if (!message) { if (relation === comparableRelation) { @@ -28468,8 +28655,11 @@ var ts; return result; } } - else if (target.flags & 1048576 && source.indexType === target.indexType) { + else if (target.flags & 1048576) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -28574,6 +28764,9 @@ var ts; if (!(targetProp.flags & 4194304)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { @@ -28755,6 +28948,9 @@ var ts; var result = -1; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, undefined)) { + continue; + } if (kind === 0 || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -28895,7 +29091,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -29049,17 +29245,24 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } return result; } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 : compareTypes(source.type, target.type); + } function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -29082,7 +29285,7 @@ var ts; var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288); }); return primaryTypes.length ? getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288) : - getUnionType(types, true); + getUnionType(types, 2); } function getCommonSubtype(types) { return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); @@ -29141,8 +29344,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -29311,7 +29514,7 @@ var ts; if (type.flags & 131072) { var unionContext_1 = context || createWideningContext(undefined, undefined, type.types); var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 ? t : getWidenedTypeWithContext(t, unionContext_1); }); - return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 : 1); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -29387,6 +29590,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -29441,6 +29647,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -29451,6 +29658,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -29482,7 +29690,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -29492,40 +29700,43 @@ var ts; var indexInfo = type.flags & 2 ? createIndexInfo(emptyObjectType, false) : undefined; return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } - function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { + function inferTypeForHomomorphicMappedType(source, target) { + var key = source.id + "," + target.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target) { var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0); - if (properties.length === 0 && !indexInfo) { + if (properties.length === 0 && !getIndexInfoOfType(source, 0)) { return undefined; } - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var inference = createInferenceInfo(typeParameter); - var inferences = [inference]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 16777216; - var members = ts.createSymbolTable(); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var propType = getTypeOfSymbol(prop); - if (propType.flags & 16777216) { + if (getTypeOfSymbol(prop).flags & 16777216) { return undefined; } - var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); - inferredProp.declarations = prop.declarations; - inferredProp.type = inferTargetType(propType); - members.set(prop.escapedName, inferredProp); - } - if (indexInfo) { - indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); - return inference.candidates ? getUnionType(inference.candidates, true) : emptyObjectType; } + var reversed = createObjectType(2048 | 16, undefined); + reversed.source = source; + reversed.mappedType = target; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + } + function inferReverseMappedType(sourceType, target) { + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return inference.candidates ? getUnionType(inference.candidates, 2) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -29540,10 +29751,11 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { + function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -29592,22 +29804,27 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - var p = priority | (source === implicitNeverType ? 16 : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { + if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) { var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -29622,15 +29839,15 @@ var ts; } } else if (source.flags & 524288 && target.flags & 524288) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1; + contravariant = !contravariant; } else if (source.flags & 1048576 && target.flags & 1048576) { inferFromTypes(source.objectType, target.objectType); @@ -29652,7 +29869,7 @@ var ts; } if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2; + priority |= 1; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -29691,9 +29908,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -29720,16 +29937,10 @@ var ts; if (constraintType.flags & 524288) { var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); - if (ts.contains(mappedTypeStack, key)) { - return; - } - (mappedTypeStack || (mappedTypeStack = [])).push(key); - var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); - mappedTypeStack.pop(); + var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4; + priority |= 2; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -29771,8 +29982,10 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromContravariantTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); @@ -29799,8 +30012,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -29828,7 +30041,7 @@ var ts; if (candidates.length > 1) { var objectLiterals = ts.filter(candidates, isObjectLiteralType); if (objectLiterals.length) { - var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, true)); + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2)); return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); } } @@ -29845,10 +30058,16 @@ var ts; !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = inference.priority & 1 ? getCommonSubtype(baseCandidates) : - context.flags & 1 || inference.priority & 8 ? getUnionType(baseCandidates, true) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 || inference.priority & 4 ? + getUnionType(baseCandidates, 2) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + if (inferredType.flags & 16384 && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2) { inferredType = silentNeverType; @@ -29888,7 +30107,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -30066,8 +30285,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -30131,14 +30350,6 @@ var ts; return 8388607; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576) { - 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) { @@ -30175,7 +30386,7 @@ var ts; parent.parent.kind === 217 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -30214,7 +30425,7 @@ var ts; var type = pattern.kind === 175 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -30325,15 +30536,15 @@ var ts; } return f(type) ? type : neverType; } - function mapType(type, mapper) { + function mapType(type, mapper, noReductions) { if (!(type.flags & 131072)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30347,7 +30558,7 @@ var ts; } } } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 : 1) : mappedType; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -30388,7 +30599,7 @@ var ts; return elementType.flags & 16384 ? autoArrayType : createArrayType(elementType.flags & 131072 ? - getUnionType(elementType.types, true) : + getUnionType(elementType.types, 2) : elementType); } function getFinalArrayType(evolvingArrayType) { @@ -30402,8 +30613,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 16384)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -30444,10 +30655,7 @@ var ts; var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } + return apparentType !== unknownType && ts.some(getSignaturesOfType(apparentType, 0), signatureHasTypePredicate); } } return false; @@ -30656,7 +30864,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 : 1), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { var id = getFlowNodeId(flow); @@ -30673,7 +30881,7 @@ var ts; } for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1), true); } } var antecedentTypes = []; @@ -30703,7 +30911,7 @@ var ts; break; } } - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 : 1); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, true); } @@ -30734,6 +30942,23 @@ var ts; } return type; } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (131072 | 65536)) || (type.flags & 32768 && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { case 58: @@ -30745,10 +30970,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 && right_1.kind === 9) { + if (left_1.kind === 190 && (right_1.kind === 9 || right_1.kind === 13)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 && left_1.kind === 9) { + if (right_1.kind === 190 && (left_1.kind === 9 || left_1.kind === 13)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -30769,6 +30994,12 @@ var ts; break; case 93: return narrowTypeByInstanceof(type, expr, assumeTrue); + case 92: + var target = getReferenceCandidate(expr.right); + if ((expr.left.kind === 9 || expr.left.kind === 13) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; case 26: return narrowType(type, expr.right, assumeTrue); } @@ -30846,7 +31077,7 @@ var ts; var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); var caseType = discriminantType.flags & 16384 ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -30913,7 +31144,7 @@ var ts; return type; } var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; + var predicate = getTypePredicateOfSignature(signature); if (!predicate) { return type; } @@ -31033,18 +31264,24 @@ var ts; var parent = node.parent; return parent.kind === 180 || parent.kind === 182 && parent.expression === node || - parent.kind === 181 && parent.expression === node; + parent.kind === 181 && parent.expression === node || + parent.kind === 204 || + parent.kind === 177 && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } - function getDeclaredOrApparentType(symbol, node) { - var type = getTypeOfSymbol(symbol); + function getApparentTypeForLocation(type, node) { if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } return type; } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -31063,8 +31300,8 @@ var ts; getNodeLinks(container).flags |= 8192; return getTypeOfSymbol(symbol); } - if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; @@ -31099,7 +31336,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3)) { @@ -31130,12 +31367,13 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); while (flowContainer !== declarationContainer && (flowContainer.kind === 187 || flowContainer.kind === 188 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 247) || node.parent.kind === 204 || @@ -31291,6 +31529,14 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 187 && @@ -31321,10 +31567,6 @@ var ts; return type; } } - if (noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -31514,7 +31756,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -31535,7 +31777,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); indexOfParameter -= 1; @@ -31554,7 +31796,7 @@ var ts; } function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer || node.kind === 58) { + if (ts.hasInitializer(declaration) && node === declaration.initializer) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -31638,7 +31880,7 @@ var ts; } function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); @@ -31663,11 +31905,6 @@ var ts; case 53: case 26: return node === right ? getContextualType(binaryExpression) : undefined; - case 34: - case 32: - case 35: - case 33: - return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; default: return undefined; } @@ -31692,10 +31929,10 @@ var ts; return mapType(type, function (t) { var prop = t.flags & 458752 ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; - }); + }, true); } function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, true); } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 131072 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); @@ -31820,11 +32057,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 198: return getContextualTypeForYieldOperand(parent); - case 183: - if (node.kind === 94) { - return getContextualType(parent); - } case 182: + case 183: return getContextualTypeForArgument(parent, node); case 185: case 203: @@ -31858,12 +32092,6 @@ var ts; case 252: case 251: return getAttributesTypeFromJsxOpeningLikeElement(parent); - case 261: { - if (node.kind === 73) { - var switchStatement = parent.parent.parent; - return getTypeOfExpression(switchStatement.expression); - } - } } return undefined; } @@ -31872,7 +32100,7 @@ var ts; return node ? node.contextualMapper : identityMapper; } function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); + var signatures = getSignaturesOfType(type, 0); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -31918,8 +32146,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -31936,7 +32164,6 @@ var ts; var result; if (signatureList) { result = cloneSignature(signatureList[0]); - result.resolvedReturnType = undefined; result.unionSignatures = signatureList; } return result; @@ -31994,7 +32221,7 @@ var ts; if (patternElement.kind !== 201) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -32004,7 +32231,7 @@ var ts; } } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : + getUnionType(elementTypes, 2) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { @@ -32051,7 +32278,7 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, 2) : undefinedType; return createIndexInfo(unionType, false); } function checkObjectLiteral(node, checkMode) { @@ -32060,7 +32287,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 0; + var propagatedFlags = 2097152; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 175 || contextualType.pattern.kind === 179); @@ -32218,12 +32445,12 @@ var ts; type.flags & 65536 && !isGenericMappedType(type) || type.flags & 393216 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node); + function checkJsxSelfClosingElement(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); return getJsxGlobalElementType() || anyType; } - function checkJsxElement(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + function checkJsxElement(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); } @@ -32232,8 +32459,8 @@ var ts; } return getJsxGlobalElementType() || anyType; } - function checkJsxFragment(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + function checkJsxFragment(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); if (compilerOptions.jsx === 2 && compilerOptions.jsxFactory) { error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); } @@ -32253,11 +32480,15 @@ var ts; ts.Debug.fail(); } } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; + } + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); var spread = emptyObjectType; - var attributesArray = []; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; @@ -32266,9 +32497,7 @@ var ts; var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; + var exprType = checkJsxAttribute(attributeDecl, checkMode); var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -32278,24 +32507,22 @@ var ts; attributeSymbol.type = exprType; attributeSymbol.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); - attributesArray.push(attributeSymbol); if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } } else { ts.Debug.assert(attributeDecl.kind === 259); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); - attributesArray = []; + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpression(attributeDecl.expression); + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 67108864); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -32303,18 +32530,8 @@ var ts; } } if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, 0); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createSymbolTable(); - for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { - var attr = attributesArray_1[_b]; - if (!filter || filter(attr)) { - attributesTable.set(attr.escapedName, attr); - } + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864); } } var parent = openingLikeElement.parent.kind === 250 ? openingLikeElement.parent : undefined; @@ -32327,18 +32544,18 @@ var ts; var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + createArrayType(getUnionType(childrenTypes)); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, 67108864); } } if (hasSpreadAnyType) { return anyType; } - var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); - return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : - typeToIntersect ? typeToIntersect : attributeType; - function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); + return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + function createJsxAttributesType() { + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); result.flags |= 67108864 | 8388608; result.objectFlags |= 128; return result; @@ -32360,7 +32577,7 @@ var ts; return childrenTypes; } function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } function getJsxType(name) { var jsxType = jsxTypes.get(name); @@ -32398,7 +32615,7 @@ var ts; } return links.resolvedSymbol; } - function getJsxElementInstanceType(node, valueType) { + function getJsxElementInstanceType(node, valueType, sourceAttributesType) { ts.Debug.assert(!(valueType.flags & 131072)); if (isTypeAny(valueType)) { return anyType; @@ -32411,19 +32628,25 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0, isJavascript); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); + } + else { + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -32536,13 +32759,12 @@ var ts; } return undefined; } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { if (elementType.flags & 131072) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), true); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + }), 2); } if (elementType.flags & 2) { return anyType; @@ -32563,14 +32785,14 @@ var ts; } return anyType; } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); if (statelessAttributesType) { return statelessAttributesType; } - if (elementClassType) { + if (elementClassType && sourceAttributesType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } if (isTypeAny(elemInstanceType)) { @@ -32630,21 +32852,26 @@ var ts; } return links.resolvedJsxElementAttributesType; } - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { + if (!sourceAttributesType) { + var links = getNodeLinks(node); + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { + var elemClassType = getJsxGlobalElementClassType(); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); + } + return links[linkLocation]; + } + else { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } - return links[linkLocation]; } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, true); + return getCustomJsxElementAttributesType(node, undefined, true); } } function getAttributesTypeFromJsxOpeningLikeElement(node) { @@ -32652,7 +32879,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, false); + return getCustomJsxElementAttributesType(node, undefined, false); } } function getJsxAttributePropertySymbol(attrib) { @@ -32695,7 +32922,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node) { + function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -32712,7 +32939,7 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node); + checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); } else { checkJsxChildren(node.parent); @@ -32738,13 +32965,11 @@ var ts; } return false; } - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, false); - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); - }); + getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, false); if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); } @@ -32753,8 +32978,13 @@ var ts; if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; - if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); + if (!ts.isJsxAttribute(attribute)) { + continue; + } + var attrName = attribute.name; + var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); break; } } @@ -32850,16 +33080,16 @@ var ts; return propKind !== 152 && propKind !== 151; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288; if (kind) { - error(errorNode, kind & 4096 ? kind & 8192 ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 ? kind & 8192 ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 | 16384) ? unknownType : t; } @@ -32873,15 +33103,20 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var propType; - var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; var apparentType = getApparentType(getWidenedType(leftType)); if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } return apparentType; } var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0); if (!(indexInfo && indexInfo.type)) { @@ -32898,11 +33133,6 @@ var ts; else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99); - leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && - !(isNonLocalAlias(leftSymbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { - getSymbolLinks(leftSymbol).referenced = undefined; - } getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); if (assignmentKind) { @@ -32911,7 +33141,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } if (node.kind !== 180 || assignmentKind === 1 || @@ -32965,6 +33195,9 @@ var ts; }); } function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32)) { + return false; + } var classType = getTypeOfSymbol(prop.parent); while (true) { classType = getSuperClass(classType); @@ -33011,7 +33244,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, undefined, outerName, false, false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); @@ -33093,31 +33326,42 @@ var ts; return res > max ? undefined : res; } 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; - } - else { - prop.isReferenced = true; + if (!prop || !noUnusedIdentifiers || !(prop.flags & 106500) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 && !(prop.flags & 32768))) { + return; + } + 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; + } + else { + prop.isReferenced = true; + } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 180 - ? node.expression - : node.left; + var left = node.kind === 180 ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + && (!(property.flags & 8192) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, type) { + var propType = getTypeOfFuncClassEnumModule(method); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var thisType = getThisTypeOfSignature(sig); + return !thisType || isTypeAssignableTo(type, thisType); + }); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(type, propertyName); @@ -33370,10 +33614,15 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } + function inferJsxTypeArguments(signature, sourceAttributesType, context) { + var paramType = getTypeAtPosition(signature, 0); + inferTypes(context.inferences, sourceAttributesType, paramType); + return getInferredTypes(context); + } function inferTypeArguments(node, signature, args, excludeArgument, context) { for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { var inference = _a[_i]; @@ -33390,7 +33639,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); } } var thisType = getThisTypeOfSignature(signature); @@ -33433,7 +33682,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -33833,7 +34082,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, true)] = false; + excludeArgument[excludeArgument.indexOf(true)] = false; } else { excludeArgument = undefined; @@ -33870,7 +34119,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -33891,7 +34140,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); } return resolveErrorCall(node); } @@ -33945,7 +34194,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -33983,6 +34232,24 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -33995,7 +34262,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -34037,6 +34304,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -34056,8 +34324,8 @@ var ts; if (elementType.flags & 131072) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -34203,16 +34471,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default")) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152, "default"); newSymbol.target = resolveSymbol(symbol); @@ -34220,7 +34490,7 @@ var ts; var anonymousSymbol = createSymbol(2048, "__type"); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 && type.symbol.flags & (1536 | 3)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -34298,7 +34568,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks) { var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { + if (declaration && ts.hasInitializer(declaration)) { return getOptionalType(type); } } @@ -34401,7 +34671,6 @@ var ts; return promiseType; } function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } @@ -34414,9 +34683,9 @@ var ts; } } else { - var types = void 0; + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (functionFlags & 1) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 ? createAsyncIterableIteratorType(anyType) @@ -34428,7 +34697,6 @@ var ts; } } else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) { return functionFlags & 2 ? createPromiseReturnType(func, neverType) @@ -34440,8 +34708,9 @@ var ts; : voidType; } } - type = getUnionType(types, true); + type = getUnionType(types, 2); } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!contextualSignature) { reportErrorsFromWidening(func, type); } @@ -34540,8 +34809,7 @@ var ts; hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 187 || func.kind === 188)) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -34549,6 +34817,17 @@ var ts; } return aggregatedTypes; } + function mayReturnNever(func) { + switch (func.kind) { + case 187: + case 188: + return true; + case 152: + return func.parent.kind === 179; + default: + return false; + } + } function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; @@ -34798,8 +35077,8 @@ var ts; } if (type.flags & 393216) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -34864,6 +35143,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -35175,7 +35457,7 @@ var ts; leftType; case 54: return getTypeFacts(leftType) & 2097152 ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], true) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : leftType; case 58: checkAssignmentOperator(rightType); @@ -35291,7 +35573,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getUnionType([type1, type2], true); + return getUnionType([type1, type2], 2); } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -35305,7 +35587,7 @@ var ts; node.contextualType = contextualType; node.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 : - contextualMapper ? 2 : 0; + contextualMapper ? 2 : 3; var result = checkExpression(node, checkMode); node.contextualType = saveContextualType; node.contextualMapper = saveContextualMapper; @@ -35314,6 +35596,9 @@ var ts; function checkExpressionCached(node, checkMode) { var links = getNodeLinks(node); if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } var saveFlowLoopStart = flowLoopStart; flowLoopStart = flowLoopCount; links.resolvedType = checkExpression(node, checkMode); @@ -35333,10 +35618,10 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 131072 && !(contextualType.flags & 8)) { - var types_19 = contextualType.types; - return ts.some(types_19, function (t) { - return !(t.flags & 128 && containsType(types_19, trueType) && containsType(types_19, falseType)) && + if (contextualType.flags & 393216 && !(contextualType.flags & 8)) { + var types_18 = contextualType.types; + return ts.some(types_18, function (t) { + return !(t.flags & 128 && containsType(types_18, trueType) && containsType(types_18, falseType)) && isLiteralOfContextualType(candidateType, t); }); } @@ -35421,9 +35706,10 @@ var ts; if (isConstEnumObjectType(type)) { var ok = (node.parent.kind === 180 && node.parent.expression === node) || (node.parent.kind === 181 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -35514,11 +35800,11 @@ var ts; case 260: return checkJsxExpression(node, checkMode); case 250: - return checkJsxElement(node); + return checkJsxElement(node, checkMode); case 251: - return checkJsxSelfClosingElement(node); + return checkJsxSelfClosingElement(node, checkMode); case 254: - return checkJsxFragment(node); + return checkJsxFragment(node, checkMode); case 258: return checkJsxAttributes(node, checkMode); case 252: @@ -35561,7 +35847,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 || func.kind === 157 || func.kind === 162) { @@ -35589,7 +35875,7 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); if (!typePredicate) { return; } @@ -35604,7 +35890,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); } } @@ -35897,22 +36183,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 && !ts.hasModifier(n, 32) && @@ -36101,6 +36371,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -36417,7 +36690,7 @@ var ts; } return undefined; } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2); } function checkAwaitedType(type, errorNode, diagnosticMessage) { return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; @@ -36443,7 +36716,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { if (errorNode) { error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); } @@ -36549,7 +36822,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } function markTypeNodeAsReferenced(node) { markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); @@ -36862,22 +37135,33 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 152 || member.kind === 150) { - if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152: + case 150: + case 154: + case 155: + if (member.kind === 155 && member.symbol.flags & 32768) { + break; } - } - else if (member.kind === 153) { + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } - } + break; + case 158: + break; + default: + ts.Debug.fail(); } } } @@ -37130,7 +37414,9 @@ var ts; } function checkVariableLikeDeclaration(node) { checkDecorators(node); - checkSourceElement(node.type); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } if (!node.name) { return; } @@ -37168,13 +37454,19 @@ var ts; } if (ts.isBindingPattern(node.name)) { if (node.initializer && node.parent.parent.kind !== 216) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + } checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 216) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -37402,7 +37694,7 @@ var ts; var arrayTypes = inputType.types; var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322); }); if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, true); + arrayType = getUnionType(filteredTypes, 2); } } else if (arrayType.flags & 524322) { @@ -37439,7 +37731,7 @@ var ts; if (arrayElementType.flags & 524322) { return stringType; } - return getUnionType([arrayElementType, stringType], true); + return getUnionType([arrayElementType, stringType], 2); } return arrayElementType; } @@ -37483,7 +37775,7 @@ var ts; } return undefined; } - var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, !!asyncMethodType); if (checkAssignability && errorNode && iteratedType) { checkTypeAssignableTo(type, asyncMethodType @@ -37522,7 +37814,7 @@ var ts; } return undefined; } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2); if (isTypeAny(nextResult)) { return undefined; } @@ -37567,48 +37859,48 @@ var ts; return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 | 1); } function checkReturnStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } + if (checkGrammarStatementInAmbientContext(node)) { + return; } var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1; + if (strictNullChecks || node.expression || returnType.flags & 16384) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { return; } - if (strictNullChecks || node.expression || returnType.flags & 16384) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 155) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } + else if (func.kind === 155) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 153) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } + } + else if (func.kind === 153) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + checkTypeAssignableTo(awaitedType, promisedType, node); } } + else { + checkTypeAssignableTo(exprType, returnType, node); + } } - else if (func.kind !== 153 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } + } + else if (func.kind !== 153 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkWithStatement(node) { @@ -37754,7 +38046,7 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -37855,9 +38147,10 @@ var ts; } var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; + if (sourceConstraint) { + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } } var sourceDefault = source.default && getTypeFromTypeNode(source.default); var targetDefault = getDefaultFromTypeParameter(target); @@ -37927,7 +38220,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -37953,7 +38249,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + var genericDiag = t.symbol && t.symbol.flags & 32 ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -37968,6 +38270,32 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1); if (signatures.length) { @@ -38234,6 +38562,7 @@ var ts; case 37: return left + right; case 38: return left - right; case 42: return left % right; + case 40: return Math.pow(left, right); } } break; @@ -39325,6 +39654,7 @@ var ts; } return undefined; case 9: + case 13: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 239 || node.parent.kind === 245) && node.parent.moduleSpecifier === node) || ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { @@ -39421,7 +39751,7 @@ var ts; ts.Debug.assert(expr.parent.kind === 178); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } function getPropertySymbolOfDestructuringAssignment(location) { var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); @@ -39455,35 +39785,28 @@ var ts; return ts.typeHasCallOrConstructSignatures(type, checker); } function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6) { - var symbols_4 = []; - var name_4 = symbol.escapedName; - ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_4); - if (symbol) { - symbols_4.push(symbol); - } - }); - return symbols_4; + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); } else if (symbol.flags & 33554432) { - var transient = symbol; - if (transient.leftSpread) { - return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); - } - if (transient.syntheticOrigin) { - return getRootSymbols(transient.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; } - return [symbol]; + return target; } function isArgumentsLocalBinding(node) { if (!ts.isGeneratedIdentifier(node)) { @@ -39772,20 +40095,20 @@ var ts; : unknownType; if (type.flags & 1024 && type.symbol === symbol) { - flags |= 131072; + flags |= 1048576; } - if (flags & 8192) { + if (flags & 131072) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -40350,9 +40673,6 @@ var ts; } } function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } if (typeParameters && typeParameters.length === 0) { var start = typeParameters.pos - "<".length; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; @@ -40435,6 +40755,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 || type.flags & 4) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32, true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -40857,12 +41184,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 || node.name.kind === 175) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } @@ -41047,7 +41377,7 @@ var ts; if (node.flags & 2097152 && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 2097152 || ts.hasModifier(node, 32 | 128))) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } @@ -41268,7 +41598,7 @@ var ts; var node = createSynthesizedNode(71); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; - node.autoGenerateKind = 0; + node.autoGenerateFlags = 0; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -41283,20 +41613,23 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1; + name.autoGenerateFlags = 1; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16; + } return name; } ts.createTempVariable = createTempVariable; function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2; + name.autoGenerateFlags = 2; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -41304,7 +41637,7 @@ var ts; ts.createLoopVariable = createLoopVariable; function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3; + name.autoGenerateFlags = 3; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -41312,10 +41645,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4; + name.autoGenerateFlags = 4; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8; + } nextAutoGenerateId++; return name; } @@ -41607,11 +41942,12 @@ var ts; : node; } ts.updateIndexSignature = updateIndexSignature; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -44218,7 +44554,9 @@ var ts; } ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; function parenthesizeSubexpressionOfConditionalExpression(e) { - return e.kind === 195 && e.operatorToken.kind === 26 + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 && emittedExpression.operatorToken.kind === 26 || + emittedExpression.kind === 293 ? ts.createParen(e) : e; } @@ -44714,6 +45052,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -44823,7 +45162,7 @@ var ts; } switch (kind) { case 71: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145: @@ -44963,7 +45302,7 @@ var ts; case 216: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219: @@ -45701,6 +46040,7 @@ var ts; var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -45780,7 +46120,10 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + value = ensureIdentifier(flattenContext, value, false, location); + } + else if (needsValue) { value = ensureIdentifier(flattenContext, value, true, location); } else if (ts.nodeIsSynthesized(node)) { @@ -45810,6 +46153,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { var pendingExpressions; var pendingDeclarations = []; @@ -45826,6 +46189,13 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + initializer = ensureIdentifier(flattenContext, initializer, false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(undefined); @@ -46496,10 +46866,13 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16; + classAliases[ts.getOriginalNodeId(node)] = alias; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); @@ -47796,12 +48169,13 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var enabledSubstitutions; var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -47836,6 +48210,82 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209: + return visitVariableStatementInAsyncBody(node); + case 215: + return visitForStatementInAsyncBody(node); + case 216: + return visitForInStatementInAsyncBody(node); + case 217: + return visitForOfStatementInAsyncBody(node); + case 264: + return visitCatchClauseInAsyncBody(node); + case 208: + case 222: + case 236: + case 261: + case 262: + case 225: + case 213: + case 214: + case 212: + case 221: + case 223: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } function visitAwaitExpression(node) { return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } @@ -47859,6 +48309,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -47866,10 +48383,17 @@ var ts; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; var isArrowFunction = node.kind === 188; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); @@ -47883,27 +48407,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -48133,7 +48658,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2) { var statement = ts.unwrapInnermostStatementOfLabel(node); if (statement.kind === 217 && statement.awaitModifier) { return visitForOfStatement(statement, node); @@ -48145,8 +48670,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -48561,7 +49086,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncIterator) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -49514,7 +50039,7 @@ var ts; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), extendsClauseElement)); + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), extendsClauseElement)); } } function addConstructor(statements, node, extendsClauseElement) { @@ -52893,7 +53418,7 @@ var ts; var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), @@ -52905,6 +53430,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; @@ -52928,7 +53455,7 @@ var ts; ]))) ]))) ], true), undefined)); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, undefined, [ ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ ts.createParameter(undefined, undefined, undefined, "require"), @@ -52936,6 +53463,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ])) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function collectAsynchronousDependencies(node, includeNonAmdDependencies) { var aliasedModuleNames = []; @@ -52968,6 +53497,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); var statements = []; @@ -52976,6 +53516,9 @@ var ts; ts.append(statements, createUnderscoreUnderscoreESModule()); } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); ts.addRange(statements, endLexicalEnvironment()); @@ -53086,11 +53629,20 @@ var ts; ts.setEmitFlags(func, 8); } } - return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), undefined, [requireCall]); + } var func; if (languageVersion >= 2) { func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); @@ -53103,6 +53655,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]); + } + return innerExpr; + } function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); @@ -53113,10 +53679,10 @@ var ts; else { var variables = []; if (namespaceDeclaration && !ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); } @@ -53578,6 +54144,16 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -53591,6 +54167,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); + context.enableSubstitution(266); context.enableSubstitution(195); context.enableSubstitution(193); context.enableSubstitution(194); @@ -54306,6 +54883,31 @@ var ts; if (hint === 1) { return substituteExpression(node); } + else if (hint === 4) { + return substituteUnspecified(node); + } + return node; + } + function substituteUnspecified(node) { + switch (node.kind) { + case 266: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), node); + } + } + } return node; } function substituteExpression(node) { @@ -54432,7 +55034,9 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + var tslibImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -54827,7 +55431,7 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { write("export {};"); writeLine(); } @@ -54987,9 +55591,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 | - 16384 | - (shouldUseResolverType ? 8192 : 0); + var format = 4096 | 8 | 4 | + 2048 | + (shouldUseResolverType ? 131072 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -55002,7 +55606,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); errorNameNode = undefined; } } @@ -55232,12 +55836,15 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); write(";"); writeLine(); return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; + } if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -55320,6 +55927,7 @@ var ts; if (node.parent.kind === 269) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { + resultHasExternalModuleIndicator = true; write("export "); } if (modifiers & 512) { @@ -55452,6 +56060,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -55866,7 +56475,7 @@ var ts; } } function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - if (node.type) { + if (ts.hasType(node)) { write(": "); emitType(node.type); } @@ -56369,7 +56978,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -56591,9 +57200,9 @@ var ts; setSourceFile(oldSource); } } - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -56602,7 +57211,7 @@ var ts; if ((emitFlags & 128) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256) === 0 && tokenPos >= 0) { @@ -56618,7 +57227,7 @@ var ts; currentSourceText = currentSource.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -57007,7 +57616,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); @@ -57017,7 +57625,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -57026,7 +57637,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -57140,7 +57754,7 @@ var ts; } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -57200,14 +57814,27 @@ var ts; var generatedNames; var tempFlagsStack; var tempFlags; + var reservedNamesStack; + var reservedNames; var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -57230,6 +57857,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -57245,6 +57876,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -57272,7 +57913,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -57298,6 +57939,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0; + reservedNamesStack = []; comments.reset(); setWriter(undefined); } @@ -57359,13 +58001,15 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -57585,7 +58229,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -57606,7 +58250,7 @@ var ts; case 101: case 99: case 91: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; case 178: return emitArrayLiteralExpression(node); @@ -57689,19 +58333,20 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + writeStringLiteral(text); } } function emitIdentifier(node) { - write(getTextOfNode(node, false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, false), node.symbol); + emitList(node, node.typeArguments, 26896); } function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -57713,51 +58358,61 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -57766,8 +58421,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -57779,13 +58434,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 ? "get " : "set "); + writeKeyword(node.kind === 154 ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -57794,31 +58450,34 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -57828,7 +58487,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -57850,34 +58511,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; emitList(node, node.members, flags | 262144); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260); @@ -57886,29 +58552,29 @@ var ts; emitList(node, node.types, 264); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -57916,54 +58582,47 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); } function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432); - write("}"); - } + writePunctuation("{"); + emitList(node, node.elements, 262576); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304); - write("]"); - } + writePunctuation("["); + emitList(node, node.elements, 262448); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitArrayLiteralExpression(node) { var elements = node.elements; @@ -57997,7 +58656,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -58018,9 +58677,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -58028,26 +58687,27 @@ var ts; emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -58060,30 +58720,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -58095,7 +58759,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26; @@ -58104,7 +58768,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, true); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -58132,12 +58796,12 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -58150,17 +58814,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } function emitTemplateSpan(node) { @@ -58168,12 +58834,12 @@ var ts; emit(node.literal); } function emitBlock(node) { - writeToken(17, node.pos, node); + writeToken(17, node.pos, writePunctuation, node); emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18, node.statements.end, node); + writeToken(18, node.statements.end, writePunctuation, node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; @@ -58182,27 +58848,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90, node.pos, node); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(90, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, node); + writeToken(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82, node.thenStatement.end, node); + writeToken(82, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -58211,55 +58877,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -58273,58 +58947,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, contextNode); + pos = writeToken(token, pos, writer, contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96, node.pos, node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(98, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20, node.expression.end); - write(" "); + writeToken(20, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -58332,21 +59010,23 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78, node.pos); - write(";"); + writeToken(78, node.pos, writeKeyword); + writeSemicolon(); } function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272); } function emitFunctionDeclaration(node) { @@ -58355,9 +59035,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -58387,19 +59067,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { if (ts.getEmitFlags(body) & 1) { @@ -58426,7 +59106,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -58438,7 +59119,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18, body.statements.end, body); + writeToken(18, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -58462,17 +59143,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -58480,66 +59165,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512) { - write(node.flags & 16 ? "namespace " : "module "); + writeKeyword(node.flags & 16 ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17, node.pos); + writeToken(17, node.pos, writePunctuation); emitList(node, node.clauses, 65); - writeToken(18, node.clauses.end); + writeToken(18, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71) { @@ -58551,23 +59247,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -58577,28 +59280,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -58607,21 +59326,24 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitJsxElement(node) { emit(node.openingElement); @@ -58629,13 +59351,13 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -58643,44 +59365,45 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -58692,13 +59415,15 @@ var ts; } } function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -58711,31 +59436,32 @@ var ts; } var format = 81985; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 | 64); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272); } function emitCatchClause(node) { - var openParenPos = writeToken(74, node.pos); - write(" "); + var openParenPos = writeToken(74, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19, openParenPos); + writeToken(19, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration.end); - write(" "); + writeToken(20, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); var initializer = node.initializer; if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512) === 0) { var commentRange = ts.getCommentRange(initializer); @@ -58746,19 +59472,21 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitSourceFile(node) { writeLine(); @@ -58841,33 +59569,60 @@ var ts; } } } + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } } - function emitNodeWithPrefix(prefix, node, emit) { + function emitWithLeadingSpace(node) { if (node) { - write(prefix); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1) { - write(" "); + writeSpace(); emit(node); } else { @@ -58881,13 +59636,16 @@ var ts; emitList(parentNode, decorators, 24577); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960); + emitList(parentNode, typeArguments, 26896); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360); + emitList(parentNode, parameters, 1296); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -58907,7 +59665,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 & ~1024); + emitList(parentNode, parameters, 1296 & ~1024); } else { emitParameters(parentNode, parameters); @@ -58922,6 +59680,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28) { + case 0: + break; + case 16: + writePunctuation(","); + break; + case 4: + writeSpace(); + writePunctuation("|"); + break; + case 8: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -58940,7 +59715,7 @@ var ts; return; } if (format & 7680) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -58950,7 +59725,7 @@ var ts; writeLine(); } else if (format & 128 && !(format & 262144)) { - write(" "); + writeSpace(); } } else { @@ -58961,21 +59736,20 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128) { - write(" "); + writeSpace(); } if (format & 64) { increaseIndent(); } var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { if ((format & (3 | 64)) === 0) { increaseIndent(); @@ -58985,7 +59759,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256) { - write(" "); + writeSpace(); } } if (shouldEmitInterveningComments) { @@ -59006,9 +59780,9 @@ var ts; } var hasTrailingComma = (format & 32) && children.hasTrailingComma; if (format & 16 && hasTrailingComma) { - write(","); + writePunctuation(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { + if (previousSibling && format & 28 && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } if (format & 64) { @@ -59018,50 +59792,102 @@ var ts; writeLine(); } else if (format & 128) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -59244,16 +60070,24 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } function popNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } function generateName(name) { - if (name.autoGenerateKind === 4) { - if (name.skipNameGenerationScope) { + if ((name.autoGenerateFlags & 7) === 4) { + if (name.autoGenerateFlags & 8) { var savedTempFlags = tempFlags; popNameGenerationScope(undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -59277,7 +60111,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { @@ -59290,11 +60125,14 @@ var ts; } return true; } - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -59306,6 +60144,9 @@ var ts; ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -59372,11 +60213,11 @@ var ts; } } function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7) { case 1: - return makeTempVariableName(0); + return makeTempVariableName(0, !!(name.autoGenerateFlags & 16)); case 2: - return makeTempVariableName(268435456); + return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); case 3: return makeUniqueName(ts.idText(name)); } @@ -59389,7 +60230,7 @@ var ts; while (original) { node = original; if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 + && node.autoGenerateFlags === 4 && node.autoGenerateId !== autoGenerateId) { break; } @@ -59399,17 +60240,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0] = ""; - delimiters[16] = ","; - delimiters[4] = " |"; - delimiters[8] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28]; - } function createBracketsMap() { var brackets = []; brackets[512] = ["{", "}"]; @@ -59430,412 +60260,6 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; - ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; - ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; - ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; - ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - function createBuilder(options) { - var isModuleEmit; - var fileInfos = ts.createMap(); - var semanticDiagnosticsPerFile = ts.createMap(); - var changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - 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) { - changedFilesSet.set(path, true); - semanticDiagnosticsPerFile.delete(path); - } - function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - 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); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - 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)]; - } - var seenFiles = ts.createMap(); - 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)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - 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]; - 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(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - 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 = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - 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) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function getFilesAffectedByUpdatedShape(program, sourceFile) { - var options = program.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.mapDefinedIter(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - }); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFile]; - } - var seenFileNamesMap = ts.createMap(); - var path = sourceFile.path; - 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); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); var ts; (function (ts) { @@ -60020,23 +60444,29 @@ var ts; return errorMessage; } ts.formatDiagnostic = formatDiagnostic; - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } - function formatAndReset(text, formatStyle) { + function formatColorAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } + ts.formatColorAndReset = formatColorAndReset; function padLeft(s, length) { while (s.length < length) { s = " " + s; @@ -60049,9 +60479,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -60062,7 +60492,7 @@ var ts; context += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -60070,10 +60500,10 @@ var ts; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); - context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); - context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += redForegroundEscapeSequence; + context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += ForegroundColorEscapeSequences.Red; if (i === firstLine) { var lastCharForLine = i === lastLine ? lastLineChar : undefined; context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); @@ -60087,19 +60517,25 @@ var ts; } context += resetEscapeSequence; } - output += host.getNewLine(); - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + output += " - "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); output += context; } output += host.getNewLine(); } - return output; + return output + host.getNewLine(); } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { @@ -60307,7 +60743,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -60412,8 +60849,9 @@ var ts; ts.Debug.assert(j === resolutions.length); return result; function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); - if (resolutionToFile) { + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { return false; } var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); @@ -60537,7 +60975,7 @@ var ts; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -60635,24 +61073,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -60974,6 +61414,7 @@ var ts; && !file.isDeclarationFile) { var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(undefined, undefined, undefined); + ts.addEmitFlags(importDecl, 67108864); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -61141,7 +61582,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); @@ -61253,7 +61694,7 @@ var ts; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { @@ -61472,12 +61913,12 @@ var ts; if (emitFileName) { var emitFilePath = toPath(emitFileName); if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { - chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; if (emitFilesSeen.has(emitFileKey)) { @@ -61571,6 +62012,31 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts"); + } + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts")) || + !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx")); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } } ts.createProgram = createProgram; function getResolutionDiagnostic(options, _a) { @@ -61743,12 +62209,14 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", + "esnext.promise": "lib.esnext.promise.d.ts", }), }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -61989,6 +62457,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -62269,17 +62744,17 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; function convertEnableAutoDiscoveryToEnable(typeAcquisition) { if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - var result = { + return { enable: typeAcquisition.enableAutoDiscovery, include: typeAcquisition.include || [], exclude: typeAcquisition.exclude || [] }; - return result; } return typeAcquisition; } @@ -62692,7 +63167,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -62716,7 +63191,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } @@ -63089,8 +63564,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - return options; + return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -63171,7 +63645,6 @@ var ts; return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; @@ -63254,9 +63727,6 @@ var ts; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } - else if (invalidMultipleRecursionPatterns.test(spec)) { - return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; - } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } @@ -63517,6 +63987,7 @@ var ts; ScriptElementKindModifier["ambientModifier"] = "declare"; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -64016,7 +64487,7 @@ var ts; return isCompletedNode(n.thenStatement, sourceFile); case 211: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25); + hasChildOfKind(n, 25, sourceFile); case 178: case 176: case 181: @@ -64037,11 +64508,9 @@ var ts; case 214: return isCompletedNode(n.statement, sourceFile); case 213: - var hasWhileKeyword = findChildOfKind(n, 106, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 20, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); + return hasChildOfKind(n, 106, sourceFile) + ? nodeEndsWith(n, 20, sourceFile) + : isCompletedNode(n.statement, sourceFile); case 163: return isCompletedNode(n.exprName, sourceFile); case 190: @@ -64071,7 +64540,6 @@ var ts; return true; } } - ts.isCompletedNode = isCompletedNode; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { @@ -64103,7 +64571,7 @@ var ts; } ts.hasChildOfKind = hasChildOfKind; function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); } ts.findChildOfKind = findChildOfKind; function findContainingList(node) { @@ -64241,8 +64709,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -64429,12 +64897,16 @@ var ts; ts.typeKeywords = [ 119, 122, + 127, 130, + 95, 133, 134, 136, 137, 105, + 139, + 140, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -64453,6 +64925,27 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { @@ -64465,6 +64958,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -64474,8 +64968,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -64593,8 +65097,10 @@ var ts; } ts.textPart = textPart; var carriageReturnLineFeed = "\r\n"; - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { @@ -64613,31 +65119,23 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536; + flags |= 16384 | 1024 | 32 | 8192; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145) { - return ts.getTextOfIdentifierOrLiteral(location); - } - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 || location.parent.kind === 247) && @@ -64646,12 +65144,16 @@ var ts; ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -64676,53 +65178,6 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; - function getOpenBrace(constructor, sourceFile) { - return constructor.body.getFirstToken(sourceFile); - } - ts.getOpenBrace = getOpenBrace; - function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, false); - } - ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; - function getSourceFileImportLocation(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); - var position = 0; - if (shebang !== undefined) { - position = shebang.length; - advancePastLineBreak(); - } - var ranges = ts.getLeadingCommentRanges(text, position); - if (!ranges) - return position; - if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end; - advancePastLineBreak(); - ranges = ranges.slice(1); - } - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { - position = range.end; - advancePastLineBreak(); - continue; - } - break; - } - return position; - function advancePastLineBreak() { - if (position < text.length) { - var charCode = text.charCodeAt(position); - if (ts.isLineBreak(charCode)) { - position++; - if (position < text.length && charCode === 13 && text.charCodeAt(position) === 10) { - position++; - } - } - } - } - } - ts.getSourceFileImportLocation = getSourceFileImportLocation; function getSynthesizedDeepClone(node) { if (node === undefined) { return undefined; @@ -64744,6 +65199,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; function suppressLeadingAndTrailingTrivia(node) { ts.Debug.assert(node !== undefined); suppressLeading(node); @@ -65045,8 +65504,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } else { @@ -65428,7 +65888,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -65436,8 +65896,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -65727,23 +66187,29 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - if (kind === 4 || kind === 5) { - continue; - } - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - if (ch === 60 || ch === 62) { - pushClassification(start, width, 1); + switch (kind) { + case 4: + case 5: continue; - } - ts.Debug.assert(ch === 124 || ch === 61); - classifyDisabledMergeCode(text, start, end); + case 2: + case 3: + classifyComment(token, kind, start, width); + triviaScanner.setTextPos(end); + continue; + case 7: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + if (ch === 60 || ch === 62) { + pushClassification(start, width, 1); + continue; + } + ts.Debug.assert(ch === 124 || ch === 61); + classifyDisabledMergeCode(text, start, end); + break; + case 6: + break; + default: + ts.Debug.assertNever(kind); } } } @@ -65990,11 +66456,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -66052,7 +66518,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -66079,36 +66545,19 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span, host, undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; + for (var path in paths) { var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name", span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name", span)); } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); } } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name", span)); - } - } - }; - for (var path in paths) { - _loop_6(path); } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -66120,43 +66569,51 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } return result; } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); - if (matches) { - var result = []; - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + if (!host.readDirectory) { + return undefined; } - return undefined; + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); + var directories = tryGetDirectories(host, baseDirectory); + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); @@ -66220,10 +66677,12 @@ var ts; PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name", span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -66235,30 +66694,37 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name", span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name", span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -66379,22 +66845,48 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } + if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) + && (contextToken.kind === 72 || contextToken.kind === 77 || contextToken.kind === 71)) { + return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); 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, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 && - location && location.parent && location.parent.kind === 253) { + switch (completionData.kind) { + case 0: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1: + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2: + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + if (sourceFile.languageVariant === 1 && location && location.parent && ts.isJsxClosingElement(location.parent)) { var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -66404,45 +66896,42 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, 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, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0: + case 3: + case 2: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, true, false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning", kindModifiers: "", sortText: "1" @@ -66450,19 +66939,41 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (includeInsertTextCompletions) { + if (origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + } + } + if (insertText !== undefined && !includeInsertTextCompletions) { return undefined; } return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -66473,63 +66984,77 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); var uniques = ts.createMap(); - if (symbols) { - for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { - var symbol = symbols_5[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); - if (!entry) { - continue; - } - var name = entry.name; - if (uniques.has(name)) { - continue; - } - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { - uniques.set(name, true); - } - entries.push(entry); + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); } + entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9) { - return undefined; - } - if (node.parent.kind === 265 && - node.parent.parent.kind === 179 && - node.parent.name === node) { - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 || node.parent.kind === 245 - || ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (isEqualityExpression(node.parent)) { - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker); - } - else if (ts.isCaseOrDefaultClause(node.parent)) { - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.parent.parent.expression), typeChecker); + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + } + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174: + switch (node.parent.parent.kind) { + case 160: + return undefined; + case 172: + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265: + if (node.parent.parent.kind === 179 && + node.parent.name === node) { + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } - return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); + case 182: + case 183: + if (!ts.isRequireCall(node.parent, false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + case 239: + case 245: + case 249: + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { + return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); } } function pathCompletionsInfo(entries) { @@ -66540,11 +67065,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false, typeChecker, target, log, true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -66564,11 +67089,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccess(node, typeChecker, target, log) { - var type = typeChecker.getTypeAtLocation(node.expression); + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false, typeChecker, target, log, true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -66585,6 +67109,30 @@ var ts; } return undefined; } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "", + kind: "label", + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768) { @@ -66614,50 +67162,53 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0) { + return { type: "request", request: completionData }; } - var symbol = ts.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var typeChecker = program.getTypeChecker(); var name = entryId.name; var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); switch (symbolCompletion.type) { case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; } case "none": { - if (ts.some(getKeywordCompletions(0), function (c) { return c.name === name; })) { + if (allKeywordsCompletions().some(function (c) { return c.name === name; })) { return { name: name, kind: "keyword", @@ -66674,28 +67225,30 @@ var ts; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo && symbolOriginInfo.type === "export" + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); - var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { host: host, + program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), getCanonicalFileName: getCanonicalFileName, - symbolToken: undefined, + symbolToken: ts.tryCast(previousToken, ts.isIdentifier), kind: isDefaultExport ? 1 : 0, - }); + }).slice(0, 1); return { sourceDisplay: sourceDisplay, codeActions: codeActions }; } function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { @@ -66715,13 +67268,67 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, checker) { - var ty = checker.getContextualType(currentToken); + var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; return symbol && (symbol.flags & 384 || symbol.flags & 32 && !ts.isAbstractConstructorSymbol(symbol)) ? getFirstSymbolInChain(symbol, currentToken, checker) : undefined; } + function getContextualType(currentToken, checker) { + var parent = currentToken.parent; + switch (currentToken.kind) { + case 71: + return getContextualTypeFromParent(currentToken, checker); + case 58: + return ts.isVariableDeclaration(parent) ? checker.getContextualType(parent.initializer) : + ts.isBinaryExpression(parent) ? checker.getTypeAtLocation(parent.left) : undefined; + case 94: + return checker.getContextualType(parent); + case 73: + return getSwitchedType(ts.cast(currentToken.parent, ts.isCaseClause), checker); + default: + return isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(currentToken); + } + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 183: + return checker.getContextualType(parent); + case 195: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 261: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, 67108863, false); if (chain) @@ -66732,7 +67339,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, false); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); @@ -66743,19 +67349,19 @@ var ts; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64) { - request = { kind: "JsDocTagName" }; + return { kind: 1 }; } else { var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 }; } } } var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271) { currentToken = ts.getTokenAtPosition(sourceFile, position, true); @@ -66767,24 +67373,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - }; - } if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; @@ -66800,9 +67391,11 @@ var ts; log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; + var isJsxInitializer = false; var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); if (contextToken) { if (isCompletionListBlocker(contextToken)) { @@ -66811,16 +67404,17 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23) { - if (parent.kind === 180) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144: + node = parent.left; + break; + default: + return undefined; } } else if (sourceFile.languageVariant === 1) { @@ -66847,14 +67441,15 @@ var ts; location = contextToken; } break; + case 257: + isJsxInitializer = previousToken.kind === 58; + break; } } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5; + var isNewIdentifierLocation = false; var keywordFilters = 0; var symbols = []; var symbolToOriginInfoMap = []; @@ -66869,8 +67464,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -66878,8 +67472,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3; } else { if (!tryGetGlobalSymbols()) { @@ -66887,8 +67480,8 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; + var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); + return { kind: 0, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284: @@ -66900,9 +67493,7 @@ var ts; } } function getTypeScriptMemberSymbols() { - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2; var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); if (ts.isEntityName(node)) { @@ -66940,7 +67531,7 @@ var ts; else { for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (typeChecker.isValidPropertyAccessForCompletions((node.parent), type, symbol)) { symbols.push(symbol); } } @@ -66958,11 +67549,14 @@ var ts; return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (tryGetConstructorLikeCompletionContainer(contextToken)) { - isMemberCompletion = false; + completionKind = 5; isNewIdentifierLocation = true; keywordFilters = 2; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { getGetClassLikeCompletionSymbols(classLikeContainer); return true; @@ -66973,13 +67567,13 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3; isNewIdentifierLocation = false; return true; } } } - isMemberCompletion = false; + completionKind = 5; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -66988,37 +67582,52 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 || - scopeNode.kind === 197 || - scopeNode.kind === 260 || - scopeNode.kind === 208 || - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1; } var symbolMeanings = 793064 | 107455 | 1920 | 2097152; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + if (options.includeInsertTextCompletions && scopeNode.kind !== 269) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269: + case 197: + case 260: + case 208: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { + var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + if (isTypeCompletion) + keywordFilters = 4; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { if (ts.isExportAssignment(location.parent)) { return true; } - if (symbol && symbol.flags & 2097152) { - symbol = typeChecker.getAliasedSymbol(symbol); - } + symbol = ts.skipAlias(symbol, typeChecker); if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920); } - if (insideJsDocTagTypeExpression || - (!isContextTokenValueLocation(contextToken) && - (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + if (isTypeCompletion) { return symbolCanBeReferencedAtTypeLocation(symbol); } } @@ -67046,6 +67655,7 @@ var ts; return parentKind === 203; } } + return false; } function symbolCanBeReferencedAtTypeLocation(symbol) { symbol = symbol.exportSymbol || symbol; @@ -67063,24 +67673,18 @@ var ts; ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; - var name = symbol.name; - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } - var isDefaultExport = name === "default"; + var isDefaultExport = symbol.name === "default"; if (isDefaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(symbol); - if (localSymbol) { - symbol = localSymbol; - name = localSymbol.name; - } - else { - name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); - } + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -67196,8 +67800,7 @@ var ts; return false; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179) { @@ -67214,7 +67817,7 @@ var ts; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (!ts.isVariableLike(rootDeclaration)) throw ts.Debug.fail("Root declaration is not variable-like."); - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217; + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 217; if (!canGetType && rootDeclaration.kind === 147) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); @@ -67245,7 +67848,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -67257,7 +67860,7 @@ var ts; return true; } function getGetClassLikeCompletionSymbols(classLikeDeclaration) { - isMemberCompletion = true; + completionKind = 3; isNewIdentifierLocation = true; keywordFilters = 1; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); @@ -67381,6 +67984,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -67517,7 +68135,9 @@ var ts; case "yield": return true; } - return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + && !(ts.isClassLike(contextToken.parent) && position > previousToken.end); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153; @@ -67638,67 +68258,62 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + || symbol.flags & 1536 && ts.startsWithQuote(name) + || ts.isKnownSymbol(symbol)) { return undefined; - if (symbol.flags & 1920) { - var firstCharCode = name.charCodeAt(0); - if (ts.isSingleOrDoubleQuote(firstCharCode)) { - return undefined; - } } - if (symbol.flags & 106500) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 && - escapedName.charCodeAt(1) === 95 && - escapedName.charCodeAt(2) === 64) { + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3: return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - return allowStringLiteral ? JSON.stringify(name) : undefined; + case 0: + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2: + case 5: + case 1: + return name.charCodeAt(0) === 32 ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - return name; } var _keywordCompletions = []; - function getKeywordCompletions(keywordFilter) { - var completions = _keywordCompletions[keywordFilter]; - if (completions) { - return completions; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 72; i <= 143; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword", + kindModifiers: "", + sortText: "0" + }); } - return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); - function generateKeywordCompletions(keywordFilter) { + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0: - return getAllKeywordCompletions(); + return kind !== 139; case 1: - return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + return isClassMemberCompletionKeyword(kind); case 2: - return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); - } - } - function getAllKeywordCompletions() { - var allKeywordsCompletions = []; - for (var i = 72; i <= 143; i++) { - if (i === 139) - continue; - allKeywordsCompletions.push({ - name: ts.tokenToString(i), - kind: "keyword", - kindModifiers: "", - sortText: "0" - }); + return isConstructorParameterCompletionKeyword(kind); + case 3: + return isFunctionLikeBodyCompletionKeyword(kind); + case 4: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); } - return allKeywordsCompletions; - } - function getFilteredKeywordCompletions(filterFn) { - return ts.filter(getKeywordCompletions(0), function (entry) { return filterFn(entry.name); }); - } + })); } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -67730,14 +68345,32 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } - function isEqualityExpression(node) { - return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114: + case 112: + case 113: + case 131: + case 123: + case 115: + case 117: + case 125: + case 135: + case 139: + return false; + } + return true; } function isEqualityOperatorKind(kind) { - return kind === 32 || - kind === 33 || - kind === 34 || - kind === 35; + switch (kind) { + case 34: + case 32: + case 35: + case 33: + return true; + default: + return false; + } } function getJsDocTagAtPosition(node, position) { var jsDoc = getJsDocHavingNode(node).jsDoc; @@ -67785,10 +68418,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, true); - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { var tagName = _a.tagName; @@ -67796,7 +68426,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -67806,8 +68436,8 @@ var ts; kind: "none" }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -68828,28 +69458,21 @@ var ts; FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); - if (!referencedSymbols || !referencedSymbols.length) { - return undefined; - } - var out = []; var checker = program.getTypeChecker(); - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; - if (definition) { - out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }); - } - } - return out; + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269) { return undefined; } @@ -68864,7 +69487,7 @@ var ts; return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -68872,14 +69495,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -68890,8 +69513,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_3 = def.node; var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_4 = def.node; @@ -68899,8 +69522,8 @@ var ts; } case "keyword": { var node_5 = def.node; - var name_6 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_6, kind: "keyword", displayParts: [{ text: name_6, kind: "keyword" }] }; + var name_5 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_5, kind: "keyword", displayParts: [{ text: name_5, kind: "keyword" }] }; } case "this": { var node_6 = def.node; @@ -69014,10 +69637,11 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -69028,10 +69652,7 @@ var ts; var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { - if (!options.implementations && node.kind === 9) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -69040,7 +69661,7 @@ var ts; } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleReferenceLocation(node) { - if (node.kind !== 9) { + if (node.kind !== 9 && node.kind !== 13) { return false; } switch (node.parent.kind) { @@ -69108,10 +69729,10 @@ var ts; return undefined; } function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; - var state = new State(sourceFiles, node.kind === 123, checker, cancellationToken, searchMeaning, options, result); + var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79) { addReference(node, symbol, node, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 }, state); @@ -69132,7 +69753,20 @@ var ts; } return result; } - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function getSpecialSearchKind(node) { + switch (node.kind) { + case 123: + return 1; + case 71: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2; + } + default: + return 0; + } + } + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -69140,12 +69774,22 @@ var ts; if (ts.isImportSpecifier(parent) && parent.propertyName === node) { return checker.getImmediateAliasedSymbol(symbol); } - return symbol; - } + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); var State = (function () { - function State(sourceFiles, isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + function State(sourceFiles, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; - this.isForConstructor = isForConstructor; + this.specialSearchKind = specialSearchKind; this.checker = checker; this.cancellationToken = cancellationToken; this.searchMeaning = searchMeaning; @@ -69411,11 +70055,18 @@ var ts; getReferenceForShorthandProperty(referenceSymbol, search, state); return; } - if (state.isForConstructor) { - findConstructorReferences(referenceLocation, sourceFile, search, state); - } - else { - addReference(referenceLocation, relatedSymbol, search.location, state); + switch (state.specialSearchKind) { + case 0: + addReference(referenceLocation, relatedSymbol, search.location, state); + break; + case 1: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } @@ -69498,22 +70149,45 @@ var ts; addRef(referenceLocation); } } - function findConstructorReferences(referenceLocation, sourceFile, search, state) { + function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { addReference(referenceLocation, search.symbol, search.location, state); } - var pusher = state.referenceAdder(search.symbol, search.location); + var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); - findOwnConstructorReferences(search.symbol, sourceFile, pusher); + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } else { var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); - if (classExtending && ts.isClassLike(classExtending)) { - findSuperConstructorAccesses(classExtending, pusher); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); } } } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, search.location, state); + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.parent.name === referenceLocation); + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + } + } + function addStaticThisReferences(classLike, pusher) { + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32))) { + continue; + } + member.body.forEachChild(function cb(node) { + if (node.kind === 99) { + pusher(node); + } + else if (!ts.isFunctionLike(node)) { + node.forEachChild(cb); + } + }); + } + } function getPropertyAccessExpressionFromRightHandSide(node) { return ts.isRightSideOfPropertyAccess(node) && node.parent; } @@ -69576,7 +70250,7 @@ var ts; var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { var parent = containingTypeReference.parent; - if (ts.isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) { + if (ts.hasType(parent) && parent.type === containingTypeReference && ts.hasInitializer(parent) && isImplementationExpression(parent.initializer)) { addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { @@ -69834,7 +70508,7 @@ var ts; } } function populateSearchSymbolSet(symbol, location, checker, implementations) { - var result = [symbol]; + var result = []; var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { if (containingObjectLiteralElement.kind !== 266) { @@ -69843,9 +70517,10 @@ var ts; result.push(propertySymbol); } } - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - ts.addRange(result, checker.getRootSymbols(contextualSymbol)); - }); + for (var _i = 0, _a = getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker); _i < _a.length; _i++) { + var contextualSymbol = _a[_i]; + addRootSymbols(contextualSymbol); + } var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); if (shorthandValueSymbol) { result.push(shorthandValueSymbol); @@ -69862,9 +70537,7 @@ var ts; function addRootSymbols(sym) { for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { var rootSymbol = _a[_i]; - if (rootSymbol !== sym) { - result.push(rootSymbol); - } + result.push(rootSymbol); if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); } @@ -69923,9 +70596,7 @@ var ts; } var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); - }); + var contextualSymbol = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), findRootSymbol); if (contextualSymbol) { return contextualSymbol; } @@ -69942,16 +70613,16 @@ var ts; } return findRootSymbol(referenceSymbol); function findRootSymbol(sym) { - return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { if (search.includes(rootSymbol)) { return rootSymbol; } if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })) { return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); return ts.find(result, search.includes); } return undefined; @@ -69969,26 +70640,11 @@ var ts; return ts.getTextOfIdentifierOrLiteral(node.name); } function getPropertySymbolsFromContextualType(node, checker) { - var objectLiteral = node.parent; - var contextualType = checker.getContextualType(objectLiteral); + var contextualType = checker.getContextualType(node.parent); var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol = contextualType.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - if (contextualType.flags & 131072) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; + var symbol = contextualType && name && contextualType.getProperty(name); + return symbol ? [symbol] : + contextualType && contextualType.flags & 131072 ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; } function getIntersectingMeaningFromDeclarations(meaning, declarations) { if (declarations) { @@ -70010,14 +70666,12 @@ var ts; if (!node) { return false; } - else if (ts.isVariableLike(node)) { - if (node.initializer) { - return true; - } - else if (node.kind === 227) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2); - } + else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { + return true; + } + else if (node.kind === 227) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2); } else if (ts.isFunctionLike(node)) { return !!node.body || ts.hasModifier(node, 2); @@ -70093,18 +70747,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - } - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { @@ -70160,32 +70805,35 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 && !(type.flags & 16)) { - var result_6 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(result_6, getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_6; - } - if (!type.symbol) { - return undefined; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -70223,55 +70871,27 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isNewExpressionTarget(location) || location.kind === 123) { - if (symbol.flags & 32) { - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { + if (ts.isNewExpressionTarget(node) || node.kind === 123 && symbol.flags & 32) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; - } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; + return undefined; } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -70319,6 +70939,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -70354,7 +70975,6 @@ var ts; (function (ts) { var JsDoc; (function (JsDoc) { - var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -70402,18 +71022,29 @@ var ts; function getJsDocCommentsFromDeclarations(declarations) { var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289: + return [declaration]; + case 288: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { var tags = []; forEachUnique(declarations, function (declaration) { @@ -70443,16 +71074,19 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -70541,25 +71175,33 @@ var ts; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - return singleLineTemplate; + return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.kind === 10) { + if (commentOwner.getStart() < position) { return undefined; } - if (commentOwner.getStart() < position || parameters.length === 0) { - return singleLineTemplate; + if (!parameters || parameters.length === 0) { + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = parameters.map(function (_a, i) { - var name = _a.name; - var nameText = ts.isIdentifier(name) ? name.text : "param" + i; - var type = isJavaScriptFile ? "{any} " : ""; - return indentationStr + " * @param " + type + nameText + newLine; - }).join(""); + var docParams = ""; + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } + } var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + @@ -70578,16 +71220,25 @@ var ts; case 151: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; + case 230: + case 231: + case 149: + case 233: + case 268: + case 232: + return { commentOwner: commentOwner }; case 209: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; } case 269: return undefined; + case 234: + return commentOwner.parent.kind === 234 ? undefined : { commentOwner: commentOwner }; case 195: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0) { @@ -70596,10 +71247,6 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } - case 10: { - var parameters_3 = ts.emptyArray; - return { commentOwner: commentOwner, parameters: parameters_3 }; - } } } } @@ -70760,8 +71407,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_7.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -70903,8 +71550,8 @@ var ts; } function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -70966,8 +71613,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -72432,9 +73079,16 @@ var ts; symbol.parent.flags & 1536) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9) { @@ -72714,6 +73368,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, undefined, undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -72729,14 +73384,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 | 3112960; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19)); @@ -72744,7 +73405,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -72765,7 +73434,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 | 3112960); + printer.writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -72776,7 +73446,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -72883,12 +73554,16 @@ var ts; return ""; } function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) : ""; + var symbolModifiers = symbol && symbol.flags & 16777216 ? + "optional" + : ""; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -72898,6 +73573,8 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 && ts.isExpression(location); var type; + var printer; + var documentationFromAlias; if (symbolKind !== "" || symbolFlags & 32 || symbolFlags & 2097152) { if (symbolKind === "getter" || symbolKind === "setter") { symbolKind = "property"; @@ -72957,14 +73634,14 @@ var ts; displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 && type.objectFlags & 16) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 4 | 1)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16); + addSignatureDisplayParts(signature, allSignatures, 262144); break; default: addSignatureDisplayParts(signature, allSignatures); @@ -73000,6 +73677,7 @@ var ts; } } if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200)) { pushTypePart("local class"); } @@ -73011,14 +73689,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -73026,10 +73704,10 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608)); } if (symbolFlags & 384) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76)); displayParts.push(ts.spacePart()); @@ -73039,7 +73717,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234); var isNamespace = declaration && declaration.name && declaration.name.kind === 71; displayParts.push(ts.keywordPart(isNamespace ? 129 : 128)); @@ -73047,7 +73725,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20)); @@ -73073,7 +73751,7 @@ var ts; else if (declaration.kind !== 156 && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); } else if (declaration.kind === 232) { addInPrefix(); @@ -73100,7 +73778,23 @@ var ts; } } if (symbolFlags & 2097152) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237: displayParts.push(ts.keywordPart(84)); @@ -73146,7 +73840,7 @@ var ts; if (symbolKind !== "") { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99)); } else { @@ -73161,7 +73855,8 @@ var ts; displayParts.push(ts.spacePart()); if (type.symbol && type.symbol.flags & 262144) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -73209,26 +73904,45 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias"); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, undefined, 1 | 2 | 4); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); - if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -73251,7 +73965,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19)); @@ -73266,7 +73980,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -73721,8 +74436,12 @@ var ts; for (var token = 0; token <= 143; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3])); @@ -73746,7 +74465,7 @@ var ts; var highPriorityCommonRules = [ rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1), rule("IgnoreAfterLineComment", 2, anyToken, formatting.anyContext, 1), - rule("NoSpaceBeforeColon", anyToken, 56, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), + rule("NotSpaceBeforeColon", anyToken, 56, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8), rule("SpaceAfterColon", 56, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2), rule("NoSpaceBeforeQuestionMark", anyToken, 55, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), rule("SpaceAfterQuestionMarkInConditionalOperator", 55, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2), @@ -73764,7 +74483,7 @@ var ts; rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44, 38, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38, 38, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38, 44, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2), - rule("NoSpaceAfterCloseBrace", 18, [22, 26, 25], [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceAfterCloseBrace", 18, [26, 25], [isNonJsxSameLineTokenContext], 8), rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18, [isMultilineBlockContext], 4), rule("SpaceAfterCloseBrace", 18, anyTokenExcept(20), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 2), rule("SpaceBetweenCloseBraceAndElse", 18, 82, [isNonJsxSameLineTokenContext], 2), @@ -73829,7 +74548,7 @@ var ts; rule("NoSpaceAfterOpenAngularBracket", 27, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), rule("NoSpaceAfterCloseAngularBracket", 29, [19, 21, 29, 26], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8), - rule("SpaceBeforeAt", anyToken, 57, [isNonJsxSameLineTokenContext], 2), + rule("SpaceBeforeAt", [20, 71], 57, [isNonJsxSameLineTokenContext], 2), rule("NoSpaceAfterAt", 57, anyToken, [isNonJsxSameLineTokenContext], 8), rule("SpaceAfterDecorator", anyToken, [ 117, @@ -73852,8 +74571,8 @@ var ts; var userConfigurableRules = [ rule("SpaceAfterConstructor", 123, 19, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2), rule("NoSpaceAfterConstructor", 123, 19, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8), - rule("SpaceAfterComma", 26, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2), - rule("NoSpaceAfterComma", 26, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8), + rule("SpaceAfterComma", 26, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2), + rule("NoSpaceAfterComma", 26, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8), rule("SpaceAfterAnonymousFunctionKeyword", 89, 19, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2), rule("NoSpaceAfterAnonymousFunctionKeyword", 89, 19, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8), rule("SpaceAfterKeywordInControl", keywords, 19, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 2), @@ -73895,6 +74614,8 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4, 1), rule("SpaceAfterTypeAssertion", 29, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2), rule("NoSpaceAfterTypeAssertion", 29, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8), + rule("SpaceBeforeTypeAnnotation", anyToken, 56, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8), ]; var lowPriorityCommonRules = [ rule("NoSpaceBeforeSemicolon", anyToken, 25, [isNonJsxSameLineTokenContext], 8), @@ -73902,10 +74623,10 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2, 1), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2, 1), rule("NoSpaceBeforeComma", anyToken, 26, [isNonJsxSameLineTokenContext], 8), - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120), 21, [isNonJsxSameLineTokenContext], 8), + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120, 73), 21, [isNonJsxSameLineTokenContext], 8), rule("NoSpaceAfterCloseBracket", 22, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8), rule("SpaceAfterSemicolon", 25, anyToken, [isNonJsxSameLineTokenContext], 2), - rule("SpaceBetweenStatements", [20, 81, 82, 73], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2), + rule("SpaceBetweenStatements", [20, 81, 82, 73], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2), rule("SpaceAfterTryFinally", [102, 87], 17, [isNonJsxSameLineTokenContext], 2), ]; return highPriorityCommonRules.concat(userConfigurableRules, lowPriorityCommonRules); @@ -73983,6 +74704,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 || + contextKind === 149 || + contextKind === 147 || + contextKind === 227 || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196; } @@ -74117,11 +74849,11 @@ var ts; function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10; } - function isNonJsxElementContext(context) { - return context.contextNode.kind !== 250; + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 250 && context.contextNode.kind !== 254; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 260; + return context.contextNode.kind === 260 || context.contextNode.kind === 259; } function isNextTokenParentJsxAttribute(context) { return context.nextTokenParent.kind === 257; @@ -74529,26 +75261,27 @@ var ts; return -1; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1) { + if (node.kind === 19 && startLine === lastIndentedLine) { + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -74577,64 +75310,52 @@ var ts; case 18: case 22: case 20: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - return indentation; - } - } - switch (kind) { - case 17: - case 18: - case 19: - case 20: - case 82: - case 106: - case 57: - return indentation; - case 41: - case 29: { - if (container.kind === 252 || - container.kind === 253 || - container.kind === 251) { - return indentation; - } - break; - } - case 21: - case 22: { - if (container.kind !== 173) { - return indentation; - } - break; - } - } - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + case 17: + case 18: + case 19: + case 20: + case 82: + case 106: + case 57: + return false; + case 41: + case 29: + switch (container.kind) { + case 252: + case 253: + case 251: + return false; + } + break; + case 21: + case 22: + if (container.kind !== 173) { + return false; + } + break; + } + return nodeStartLine !== line + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; } } @@ -74844,18 +75565,20 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 | 8) && currentStartLine !== previousStartLine) { - lineAction = 2; - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(false); - } - } - else if (rule.action & 4 && currentStartLine === previousStartLine) { - lineAction = 1; - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2: + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(false); + } + break; + case 1: + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(true); + } + break; + default: + ts.Debug.assert(lineAction === 0); } trimTrailingWhitespaces = !(rule.action & 8) && rule.flags !== 1; } @@ -74988,33 +75711,37 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1: - return; + return 0; case 8: if (previousRange.end !== currentRange.pos) { recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 : 0; } break; case 4: if (rule.flags !== 1 && previousStartLine !== currentStartLine) { - return; + return 0; } var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 : 1; } break; case 2: if (rule.flags !== 1 && previousStartLine !== currentStartLine) { - return; + return 0; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 : 0; } - break; } + return 0; } } var LineAction; @@ -75106,12 +75833,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -75121,20 +75848,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -75390,11 +76110,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { if (node.kind === 20) { @@ -75502,6 +76224,7 @@ var ts; case 176: case 175: case 252: + case 255: case 251: case 260: case 151: @@ -75547,6 +76270,8 @@ var ts; (!!child.namedBindings && child.namedBindings.kind !== 242); case 250: return childKind !== 253; + case 254: + return childKind !== 256; } return indentByDefault; } @@ -75688,10 +76413,12 @@ var ts; this.formatContext = formatContext; this.validator = validator; this.changes = []; + this.deletedNodesInLists = []; + this.nodesInsertedAtClassStarts = ts.createMap(); this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 : 0, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -75706,14 +76433,14 @@ var ts; if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -75730,6 +76457,9 @@ var ts; this.deleteNode(sourceFile, node); return this; } + var id = ts.getNodeId(node); + ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); + this.deletedNodesInLists[id] = true; if (index !== containingList.length - 1) { var nextToken = ts.getTokenAtPosition(sourceFile, node.end, false); if (nextToken && isSeparator(node, nextToken)) { @@ -75740,9 +76470,17 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); + var prev = containingList[index - 1]; + if (this.deletedNodesInLists[ts.getNodeId(prev)]) { + var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); + var end = getAdjustedEndPosition(sourceFile, node, {}); + this.deleteRange(sourceFile, { pos: pos, end: end }); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); + if (previousToken && isSeparator(node, previousToken)) { + this.deleteNodeRange(sourceFile, previousToken, node); + } } } return this; @@ -75784,37 +76522,93 @@ var ts; }); return this; }; - ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); - }; - ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes) { + this.replaceWithMultiple(sourceFile, oldNode.getStart(sourceFile), oldNode.getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; - ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); - }; - ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes) { + this.replaceWithMultiple(sourceFile, ts.first(oldNodes).getStart(sourceFile), ts.last(oldNodes).getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; - ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); }; - ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { - if (options === void 0) { options = {}; } - if ((ts.isStatementButNotDeclaration(after)) || + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { + var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { + return { suffix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(before); + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, true), { useNonAdjustedEndPosition: true }); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var startPosition = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + var firstMember = ts.firstOrUndefined(cls.members); + if (!firstMember) { + var id = ts.getNodeId(cls).toString(); + var newMembers = this.nodesInsertedAtClassStarts.get(id); + if (newMembers) { + ts.Debug.assert(newMembers.sourceFile === sourceFile && newMembers.cls === cls); + newMembers.members.push(newElement); + } + else { + this.nodesInsertedAtClassStarts.set(id, { sourceFile: sourceFile, cls: cls, members: [newElement] }); + } + } + else { + this.insertNodeBefore(sourceFile, firstMember, newElement); + } + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + if (ts.isStatementButNotDeclaration(after) || after.kind === 150 || after.kind === 149 || after.kind === 151) { @@ -75828,8 +76622,20 @@ var ts; }); } } - var endPosition = getAdjustedEndPosition(sourceFile, after, options); - return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, this.getInsertNodeAfterOptions(after)); + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + } + else if (ts.isStatement(node) || ts.isClassElement(node) || ts.isTypeElement(node)) { + return { suffix: this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(node)) { + return { prefix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(node); }; ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); @@ -75918,8 +76724,19 @@ var ts; } return this; }; + ChangeTracker.prototype.finishInsertNodeAtClassStart = function () { + var _this = this; + this.nodesInsertedAtClassStarts.forEach(function (_a) { + var sourceFile = _a.sourceFile, cls = _a.cls, members = _a.members; + var newCls = cls.kind === 230 + ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) + : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); + _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + }); + }; ChangeTracker.prototype.getChanges = function () { var _this = this; + this.finishInsertNodeAtClassStart(); var changesPerFile = ts.createMap(); for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { var c = _a[_i]; @@ -76090,6 +76907,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -76128,36 +76977,83 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; }()); + function getInsertionPositionAtSourceFileTop(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + if (ranges.length && ranges[0].kind === 3 && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 && text.charCodeAt(position) === 10) { + position++; + } + } + } + } + } })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { - var codeFixes = []; - function registerCodeFix(codeFix) { - ts.forEach(codeFix.errorCodes, function (error) { - var fixes = codeFixes[error]; - if (!fixes) { - fixes = []; - codeFixes[error] = fixes; - } - fixes.push(codeFix); - }); + var codeFixRegistrations = []; + var fixIdToRegistration = ts.createMap(); + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + var registrations = codeFixRegistrations[error]; + if (!registrations) { + registrations = []; + codeFixRegistrations[error] = registrations; + } + registrations.push(reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } } codefix.registerCodeFix = registerCodeFix; function getSupportedErrorCodes() { - return Object.keys(codeFixes); + return Object.keys(codeFixRegistrations); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; function getFixes(context) { - var fixes = codeFixes[context.errorCode]; + var fixes = codeFixRegistrations[context.errorCode]; var allActions = []; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); @@ -76176,6 +77072,41 @@ var ts; return allActions; } codefix.getFixes = getFixes; + function getAllFixes(context) { + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); + }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function codeFixAllWithTextChanges(context, errorCodes, use) { + var changes = []; + eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); + changes.sort(function (a, b) { return b.span.start - a.span.start; }); + return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); + } + codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -76183,14 +77114,14 @@ var ts; var refactor; (function (refactor_1) { var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - return ts.flatMapIter(refactors.values(), function (refactor) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); - }); + })); } refactor_1.getApplicableRefactors = getApplicableRefactors; function getEditsForRefactor(context, refactorName, actionName) { @@ -76208,102 +77139,119 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var decorator = ts.getAncestor(token, 148); - ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); - var replacement = ts.createCall(decorator.expression, undefined, undefined); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, decorator.expression, replacement); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), - changes: changeTracker.getChanges() - }]; - } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, undefined, undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var qualifiedName = ts.getAncestor(token, 144); - ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); - if (!ts.isIdentifier(qualifiedName.left)) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); } - var leftText = qualifiedName.left.getText(sourceFile); - var rightText = qualifiedName.right.getText(sourceFile); - var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, qualifiedName, replacement); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), - changes: changeTracker.getChanges() - }]; - } + }); }, }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, true), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code], - getCodeActions: getActionForClassLikeIncorrectImplementsInterface + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); + if (changes.length === 0) + return undefined; + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); + return { description: description, changes: changes, fixId: fixId }; + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + } + } + }); + }, }); - function getActionForClassLikeIncorrectImplementsInterface(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); - var checker = context.program.getTypeChecker(); - var classDeclaration = ts.getContainingClass(token); - if (!classDeclaration) { - return undefined; - } - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); + function getClass(sourceFile, pos) { + var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, false)); + ts.Debug.assert(!!classDeclaration); + return classDeclaration; + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8); }); var classType = checker.getTypeAtLocation(classDeclaration); - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(classDeclaration); - var hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, 1); - var hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, 0); - var result = []; - for (var _i = 0, implementedTypeNodes_2 = implementedTypeNodes; _i < implementedTypeNodes_2.length; _i++) { - var implementedTypeNode = implementedTypeNodes_2[_i]; - var implementedType = checker.getTypeAtLocation(implementedTypeNode); - var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8); }); - var newNodes = []; - createAndAddMissingIndexSignatureDeclaration(implementedType, 1, hasNumericIndexSignature, newNodes); - createAndAddMissingIndexSignatureDeclaration(implementedType, 0, hasStringIndexSignature, newNodes); - newNodes = newNodes.concat(codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker)); - var message = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - if (newNodes.length > 0) { - pushAction(result, newNodes, message); - } + if (!checker.getIndexTypeOfType(classType, 1)) { + createMissingIndexSignatureDeclaration(implementedType, 1); } - return result; - function createAndAddMissingIndexSignatureDeclaration(type, kind, hasIndexSigOfKind, newNodes) { - if (hasIndexSigOfKind) { - return; - } + if (!checker.getIndexTypeOfType(classType, 0)) { + createMissingIndexSignatureDeclaration(implementedType, 0); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); - if (!indexInfoOfKind) { - return; + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); } - var newIndexSignatureDeclaration = checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration); - newNodes.push(newIndexSignatureDeclaration); - } - function pushAction(result, newNodes, description) { - result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -76312,156 +77260,189 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ]; + var fixId = "addMissingMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, - ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], - getCodeActions: getActionsForAddMissingMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var addMember = inJs ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenNames = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var program = context.program; + var info = getInfo(diag.file, diag.start, program.getTypeChecker()); + if (!info) + return; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + if (!ts.addToSeen(seenNames, token.text)) { + return; + } + if (call) { + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + } + else { + if (inJs) { + addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); + addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + } + } + }); + }, }); - function getActionsForAddMissingMember(context) { - var tokenSourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(tokenSourceFile, start, false); - if (token.kind !== 71) { + function getInfo(tokenSourceFile, tokenPos, checker) { + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, false); + if (!ts.isIdentifier(token)) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent)) { + var classAndMakeStatic = getClassAndMakeStatic(token, checker); + if (!classAndMakeStatic) { + return undefined; + } + var classDeclaration = classAndMakeStatic.classDeclaration, makeStatic = classAndMakeStatic.makeStatic; + var classDeclarationSourceFile = classDeclaration.getSourceFile(); + var inJs = ts.isInJavaScriptFile(classDeclarationSourceFile); + var call = ts.tryCast(token.parent.parent, ts.isCallExpression); + return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; + } + function getClassAndMakeStatic(token, checker) { + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) { return undefined; } - var tokenName = token.getText(tokenSourceFile); - var makeStatic = false; - var classDeclaration; - if (token.parent.expression.kind === 99) { + if (parent.expression.kind === 99) { var containingClassMemberDeclaration = ts.getThisContainer(token, false); if (!ts.isClassElement(containingClassMemberDeclaration)) { return undefined; } - classDeclaration = containingClassMemberDeclaration.parent; - makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32); + var classDeclaration = containingClassMemberDeclaration.parent; + return ts.isClassLike(classDeclaration) ? { classDeclaration: classDeclaration, makeStatic: ts.hasModifier(containingClassMemberDeclaration, 32) } : undefined; } else { - var checker = context.program.getTypeChecker(); - var leftExpression = token.parent.expression; - var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 65536) { - var symbol = leftExpressionType.symbol; - if (symbol.flags & 32) { - classDeclaration = symbol.declarations && symbol.declarations[0]; - if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { - makeStatic = true; - } - } + var leftExpressionType = checker.getTypeAtLocation(parent.expression); + var symbol = leftExpressionType.symbol; + if (!(leftExpressionType.flags & 65536 && symbol.flags & 32)) { + return undefined; } + var classDeclaration = ts.cast(ts.first(symbol.declarations), ts.isClassLike); + return { classDeclaration: classDeclaration, makeStatic: leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol) }; } - if (!classDeclaration || !ts.isClassLike(classDeclaration)) { + } + function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + if (changes.length === 0) return undefined; - } - var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); - var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); - return ts.isInJavaScriptFile(classDeclarationSourceFile) ? - getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : - getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); - function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(false); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - if (makeStatic) { - if (classDeclaration.kind === 200) { - return actions; - } - var className = classDeclaration.name.getText(); - var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); - var initializeStaticAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), - changes: staticInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeStaticAction); - return actions; - } - else { - var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); - if (!classConstructor) { - return actions; - } - var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); - var initializeAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), - changes: propertyInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeAction); - return actions; - } - } - function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(true); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - var typeNode; - if (token.parent.parent.kind === 195) { - var binaryExpression = token.parent.parent; - var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); - } - typeNode = typeNode || ts.createKeywordTypeNode(119); - var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; - actions = ts.append(actions, { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: propertyChangeTracker.getChanges() - }); - if (!makeStatic) { - var stringTypeNode = ts.createKeywordTypeNode(136); - var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); - var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); - actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), - changes: indexSignatureChangeTracker.getChanges() - }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); + return { description: description, changes: changes, fixId: fixId }; + } + function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 200) { + return; } - return actions; + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); } - function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 182) { - var callExpression = token.parent.parent; - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: methodDeclarationChangeTracker.getChanges() - }; + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); } } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 195) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + } + return typeNode || ts.createKeywordTypeNode(119); + } + function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + var stringTypeNode = ts.createKeywordTypeNode(136); + var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); + var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + } + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], - getCodeActions: getActionsForCorrectSpelling + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context.program.getTypeChecker()); + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion); + }); }, }); - function getActionsForCorrectSpelling(context) { - var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var checker = context.program.getTypeChecker(); + function getInfo(sourceFile, pos, checker) { + var node = ts.getTokenAtPosition(sourceFile, pos, false); var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 71); @@ -76474,18 +77455,10 @@ var ts; ts.Debug.assert(name !== undefined, "name should be defined"); suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - if (suggestion) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: node.getStart(), length: node.getWidth() }, - newText: suggestion - }], - }], - }]; - } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); } function convertSemanticMeaningToSymbolFlags(meaning) { var flags = 0; @@ -76506,30 +77479,38 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixCannotFindModule"; + var errorCodes = [ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, - ], + errorCodes: errorCodes, 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, sourceFile.fileName, token.text); - return action && [action]; + var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); + return codeAction && [__assign({ fixId: fixId }, codeAction)]; }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { + var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + if (pkg) { + commands.push(getCommand(diag.file.fileName, pkg)); + } + }); }, }); - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + function getModuleName(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, false), ts.isStringLiteral).text; + } + function getCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function getTypesPackageNameToInstall(host, moduleName) { var packageName = ts.getPackageName(moduleName).packageName; - if (!host.isKnownTypesPackageName(packageName)) { - return undefined; - } - var typesPackageName = ts.getTypesPackageName(packageName); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; + } + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = getTypesPackageNameToInstall(host, moduleName); + return packageName === undefined ? undefined : { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), changes: [], - commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + commands: [getCommand(fileName, packageName)], }; } codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; @@ -76539,40 +77520,39 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code], - getCodeActions: getActionForClassLikeMissingAbstractMember - }); - codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code], - getCodeActions: getActionForClassLikeMissingAbstractMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + }); + return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); + }); }, }); - function getActionForClassLikeMissingAbstractMember(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); - var checker = context.program.getTypeChecker(); - if (ts.isClassLike(token.parent)) { - var classDeclaration = token.parent; - var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); - var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); - var extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType); - var abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember); - var newNodes = codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker); - var changes = codefix.newNodesToChanges(newNodes, ts.getOpenBraceOfClassLike(classDeclaration, sourceFile), context); - if (changes && changes.length > 0) { - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), - changes: changes - }]; - } - } - return undefined; + function getClass(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + var classDeclaration = token.parent; + ts.Debug.assert(ts.isClassLike(classDeclaration)); + return classDeclaration; + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { - var decls = symbol.getDeclarations(); - ts.Debug.assert(!!(decls && decls.length > 0)); - var flags = ts.getModifierFlags(decls[0]); + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); return !(flags & 8) && !!(flags & 128); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -76581,357 +77561,515 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - if (token.kind !== 99) { - return undefined; - } - var constructor = ts.getContainingFunction(token); - var superCall = findSuperCall(constructor.body); - if (!superCall) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) return undefined; - } - if (superCall.expression && superCall.expression.kind === 182) { - var expressionArguments = superCall.expression.arguments; - for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { - var arg = expressionArguments_1[_i]; - if (arg.expression === token) { - return undefined; - } - } - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); - changeTracker.deleteNode(sourceFile, superCall); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), - changes: changeTracker.getChanges() - }]; - function findSuperCall(n) { - if (n.kind === 211 && ts.isSuperCall(n.expression)) { - return n; - } - if (ts.isFunctionLike(n)) { - return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); } - return ts.forEachChild(n, findSuperCall); - } - } + }); + }, }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.deleteNode(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + ts.Debug.assert(token.kind === 99); + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - if (token.kind !== 123) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var superCall = ts.createStatement(ts.createCall(ts.createSuper(), undefined, ts.emptyArray)); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), - changes: changeTracker.getChanges() - }]; - } + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + ts.Debug.assert(token.kind === 123); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), undefined, ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); - var classDeclNode = ts.getContainingClass(token); - if (!(token.kind === 71 && ts.isClassLike(classDeclNode))) { + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 85 ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceRange(sourceFile, { pos: extendsToken.getStart(), end: extendsToken.end }, ts.createToken(108)); + if (heritageClauses.length === 2 && + heritageClauses[0].token === 85 && + heritageClauses[1].token === 108) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26)); + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; } - var heritageClauses = classDeclNode.heritageClauses; - if (!(heritageClauses && heritageClauses.length > 0)) { - return undefined; - } - var extendsToken = heritageClauses[0].getFirstToken(); - if (!(extendsToken && extendsToken.kind === 85)) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108)); - for (var i = 1; i < heritageClauses.length; i++) { - var keywordToken = heritageClauses[i].getFirstToken(); - if (keywordToken) { - changeTracker.replaceNode(sourceFile, keywordToken, ts.createToken(26)); - } - } - var result = [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), - changes: changeTracker.getChanges() - }]; - return result; + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); } - }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var errorCodes = [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); - if (token.kind !== 71) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), - changes: changeTracker.getChanges() - }]; - } + var token = getNode(sourceFile, context.span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, false), ts.isIdentifier); + } + function doChange(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, - ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, false); - if (token.kind === 21) { - token = ts.getTokenAtPosition(sourceFile, start + 1, false); + var token = getToken(sourceFile, context.span.start); + var result = []; + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + if (deletion.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); + result.push({ description: description, changes: deletion, fixId: fixIdDelete }); } - switch (token.kind) { - case 71: - return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); - case 150: - case 241: - return [deleteNode(token.parent)]; + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + if (prefix.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); + result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = getToken(diag.file, diag.start); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + tryDeleteDeclaration(changes, sourceFile, token); + break; default: - return deleteDefault(); + ts.Debug.fail(JSON.stringify(context.fixId)); } - function deleteDefault() { - if (ts.isDeclarationName(token)) { - return [deleteNode(token.parent)]; + }); }, + }); + function getToken(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, false); + return token.kind === 21 ? ts.getTokenAtPosition(sourceFile, pos + 1, false) : token; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 147: + return true; + case 227: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 217: + case 216: + return true; } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return [deleteNode(token.parent.parent)]; + } + } + return false; + } + function tryDeleteDeclaration(changes, sourceFile, token) { + switch (token.kind) { + case 71: + tryDeleteIdentifier(changes, sourceFile, token); + break; + case 150: + case 241: + changes.deleteNode(sourceFile, token.parent); + break; + default: + tryDeleteDefault(changes, sourceFile, token); + } + } + function tryDeleteDefault(changes, sourceFile, token) { + if (ts.isDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent.parent); + } + } + function tryDeleteIdentifier(changes, sourceFile, identifier) { + var parent = identifier.parent; + switch (parent.kind) { + case 227: + tryDeleteVariableDeclaration(changes, sourceFile, parent); + break; + case 146: + var typeParameters = parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); + ts.Debug.assert(previousToken.kind === 27); + ts.Debug.assert(nextToken.kind === 29); + changes.deleteNodeRange(sourceFile, previousToken, nextToken); } else { - return undefined; + changes.deleteNodeInList(sourceFile, parent); } - } - function prefixIdentifierWithUnderscore(identifier) { - var startPosition = identifier.getStart(sourceFile, false); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), - changes: [{ - fileName: sourceFile.path, - textChanges: [{ - span: { start: startPosition, length: 0 }, - newText: "_" - }] - }] - }; - } - function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { - var parent = identifier.parent; - switch (parent.kind) { - case 227: - return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 146: - var typeParameters = parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); - ts.Debug.assert(previousToken.kind === 27); - ts.Debug.assert(nextToken.kind === 29); - return [deleteNodeRange(previousToken, nextToken)]; - } - else { - return [deleteNodeInList(parent)]; - } - case 147: - var functionDeclaration = parent.parent; - var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); - return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ? [deleteAction] - : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; - case 238: - var importEquals = ts.getAncestor(identifier, 238); - return [deleteNode(importEquals)]; - case 243: - var namedImports = parent.parent; - if (namedImports.elements.length === 1) { - return deleteNamedImportBinding(namedImports); - } - else { - return [deleteNodeInList(parent)]; - } - case 240: - var importClause = parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 239); - return [deleteNode(importDecl)]; - } - else { - var start_6 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); - if (nextToken && nextToken.kind === 26) { - return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) })]; - } - else { - return [deleteNode(importClause.name)]; - } - } - case 241: - return deleteNamedImportBinding(parent); - default: - return deleteDefault(); + break; + case 147: + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } - } - function deleteNamedImportBinding(namedBindings) { - if (namedBindings.parent.name) { - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, false); - if (previousToken && previousToken.kind === 26) { - return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; - } - return undefined; + else { + changes.deleteNodeInList(sourceFile, parent); + } + break; + case 238: + var importEquals = ts.getAncestor(identifier, 238); + changes.deleteNode(sourceFile, importEquals); + break; + case 243: + var namedImports = parent.parent; + if (namedImports.elements.length === 1) { + tryDeleteNamedImportBinding(changes, sourceFile, namedImports); } else { - var importDecl = ts.getAncestor(namedBindings, 239); - return [deleteNode(importDecl)]; + changes.deleteNodeInList(sourceFile, parent); } - } - function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { - switch (varDecl.parent.parent.kind) { - case 215: - var forStatement = varDecl.parent.parent; - var forInitializer = forStatement.initializer; - return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 217: - var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 228); - var forOfInitializer = forOfStatement.initializer; - return [ - replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), - prefixIdentifierWithUnderscore(identifier) - ]; - case 216: - return [prefixIdentifierWithUnderscore(identifier)]; - default: - var variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return [deleteNode(variableStatement)]; - } - else { - return [deleteNodeInList(varDecl)]; - } + break; + case 240: + var importClause = parent; + if (!importClause.namedBindings) { + changes.deleteNode(sourceFile, ts.getAncestor(importClause, 239)); } + else { + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); + if (nextToken && nextToken.kind === 26) { + var end = ts.skipTrivia(sourceFile.text, nextToken.end, false, true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + changes.deleteNode(sourceFile, importClause.name); + } + } + break; + case 241: + tryDeleteNamedImportBinding(changes, sourceFile, parent); + break; + default: + tryDeleteDefault(changes, sourceFile, identifier); + break; + } + } + function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) { + if (namedBindings.parent.name) { + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, false); + if (previousToken && previousToken.kind === 26) { + changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); } - function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); - } - function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); - } - function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); - } - function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); + } + else { + var importDecl = ts.getAncestor(namedBindings, 239); + changes.deleteNode(sourceFile, importDecl); + } + } + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + switch (varDecl.parent.parent.kind) { + case 215: { + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + changes.deleteNode(sourceFile, forInitializer); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + break; } - function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); + case 217: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 228); + var forOfInitializer = forOfStatement.initializer; + changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); + break; + case 216: + case 225: + break; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + changes.deleteNode(sourceFile, variableStatement); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain)]; + if (typeNode.kind === 274) { + actions.push(fix(checker.getNullableType(type, 4096), fixIdNullable)); } - function makeChange(changeTracker) { + return actions; + function fix(type, fixId) { + var newText = typeString(type, checker); return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], + fixId: fixId, }; } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 274 && fixId === fixIdNullable ? checker.getNullableType(type, 4096) : type; + changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + }); } }); + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, false), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function createChange(declaration, sourceFile, newText) { + return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; + } + function typeString(type, checker) { + return checker.typeToString(type, undefined, 1); + } + function isTypeContainer(node) { + switch (node.kind) { + case 203: + case 156: + case 157: + case 229: + case 154: + case 158: + case 173: + case 152: + case 151: + case 147: + case 150: + case 149: + case 155: + case 232: + case 185: + case 227: + return true; + default: + return false; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], - getCodeActions: getActionsForJSDocTypes + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, }); - function getActionsForJSDocTypes(context) { - var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var decl = ts.findAncestor(node, function (n) { - return n.kind === 203 || - n.kind === 156 || - n.kind === 157 || - n.kind === 229 || - n.kind === 154 || - n.kind === 158 || - n.kind === 173 || - n.kind === 152 || - n.kind === 151 || - n.kind === 147 || - n.kind === 150 || - n.kind === 149 || - n.kind === 155 || - n.kind === 232 || - n.kind === 185 || - n.kind === 227; - }); - if (!decl) - return; - var checker = context.program.getTypeChecker(); - var jsdocType = decl.type; - if (!jsdocType) - return; - var original = ts.getTextOfNode(jsdocType); - var type = checker.getTypeFromTypeNode(jsdocType); - var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, undefined, 8))]; - if (jsdocType.kind === 274) { - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096), undefined, 8); - actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; } - return actions; } - function createAction(declaration, fileName, original, replacement) { + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152: + insertBefore = containingFunction.name; + break; + case 229: + case 187: + insertBefore = ts.findChildOfKind(containingFunction, 89, sourceFile); + break; + case 188: + insertBefore = ts.findChildOfKind(containingFunction, 19, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), - changes: [{ - fileName: fileName, - textChanges: [{ - span: { start: declaration.getStart(), length: declaration.getWidth() }, - newText: replacement - }] - }], + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) }; } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120, insertBefore); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; @@ -76946,7 +78084,9 @@ var ts; ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ], - getCodeActions: getImportCodeActions + getCodeActions: getImportCodeActions, + fixIds: [], + getAllCodeActions: ts.notImplemented, }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { @@ -77031,21 +78171,23 @@ var ts; return { description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), changes: changes, + fixId: undefined, kind: kind, moduleSpecifier: moduleSpecifier }; } function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var checker = context.program.getTypeChecker(); - var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, false); + var program = context.program; + var checker = program.getTypeChecker(); + var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, + program: program, checker: checker, - compilerOptions: context.program.getCompilerOptions(), + compilerOptions: program.getCompilerOptions(), cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolToken.getText(), @@ -77070,7 +78212,10 @@ var ts; var declaration = declarations_13[_i]; var namespace = getNamespaceImportName(declaration); if (namespace) { - actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } } } @@ -77113,7 +78258,7 @@ var ts; } } function getCodeActionForNewImport(context, moduleSpecifier) { - var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var kind = context.kind, sourceFile = context.sourceFile, symbolName = context.symbolName; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); @@ -77122,10 +78267,10 @@ var ts; : ts.createImportEqualsDeclaration(undefined, undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); var changes = ChangeTracker.with(context, function (changeTracker) { if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } else { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); + changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, true); } }); return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes, "NewImport", moduleSpecifierWithoutQuotes); @@ -77136,6 +78281,12 @@ var ts; literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); return literal; } + function usesJsExtensionOnImports(sourceFile) { + return ts.firstDefined(sourceFile.imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; + }) || false; + } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -77149,40 +78300,54 @@ var ts; ts.Debug.assertNever(kind); } } - function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + function getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; - var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); - if (!baseUrl) { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + var addJsExtension = usesJsExtensionOnImports(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); }); - return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + return ts.best(ts.arrayIterator(choicesForEachExportingModule), function (a, b) { return a[0].length < b[0].length; }); } codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } function getRelativePathNParents(relativePath) { var count = 0; for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { @@ -77196,10 +78361,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -77207,14 +78373,14 @@ var ts; 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); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -77229,12 +78395,12 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options); + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); } }); } @@ -77330,15 +78496,25 @@ var ts; 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); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } - function removeExtensionAndIndexPostFix(fileName, options) { + function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); - return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + return addJsExtension + ? noExtension + ".js" + : ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); @@ -77358,7 +78534,7 @@ var ts; return [fromExistingImport]; } var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); - var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.program, ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); } function moduleSpecifierFromAnyImport(node) { @@ -77402,9 +78578,10 @@ var ts; } 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); + var changes = ChangeTracker.with(context, function (tracker) { + return tracker.changeIdentifierToPropertyAccess(sourceFile, namespacePrefix, symbolToken); + }); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes, "CodeChange", undefined); } function getImportCodeActions(context) { var importFixContext = convertToImportCodeFixContext(context); @@ -77422,7 +78599,7 @@ var ts; symbolName = context.symbolName; } else if (ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken) { - symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455, false)); symbolName = symbol.name; } else { @@ -77459,8 +78636,9 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 }))); } @@ -77470,6 +78648,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default"); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -77530,22 +78723,50 @@ var ts; } return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); codefix.registerCodeFix({ - errorCodes: getApplicableDiagnosticCodes(), - getCodeActions: getDisableJsDiagnosticsCodeActions + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], + fixId: fixId, + }, + { + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [{ + span: { + start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, + length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 + }, + newText: "// @ts-nocheck" + newLineCharacter + }])], + fixId: undefined, + }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + if (err.start !== undefined) { + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); + } + }); }, }); - function getApplicableDiagnosticCodes() { - var allDiagnostcs = ts.Diagnostics; - return Object.keys(allDiagnostcs) - .filter(function (d) { return allDiagnostcs[d] && allDiagnostcs[d].category === ts.DiagnosticCategory.Error; }) - .map(function (d) { return allDiagnostcs[d].code; }); - } function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { var line = ts.getLineAndCharacterOfPosition(sourceFile, position).line; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); @@ -77565,86 +78786,29 @@ var ts; newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter }; } - function getDisableJsDiagnosticsCodeActions(context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { - return undefined; - } - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)] - }] - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { - start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, - length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 - }, - newText: "// @ts-nocheck" + newLineCharacter - }] - }] - }]; - } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; (function (ts) { var codefix; (function (codefix) { - function newNodesToChanges(newNodes, insertAfter, context) { - var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { - var newNode = newNodes_1[_i]; - changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); - } - var changes = changeTracker.getChanges(); - if (!ts.some(changes)) { - return changes; - } - ts.Debug.assert(changes.length === 1); - var consolidatedChanges = [{ - fileName: changes[0].fileName, - textChanges: [{ - span: changes[0].textChanges[0].span, - newText: changes[0].textChanges.reduce(function (prev, cur) { return prev + cur.newText; }, "") - }] - }]; - return consolidatedChanges; - } - codefix.newNodesToChanges = newNodesToChanges; - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, out) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); - var newNodes = []; - for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { - var symbol = missingMembers_1[_i]; - var newNode = createNewNodeForMemberSymbol(symbol, classDeclaration, checker); - if (newNode) { - if (Array.isArray(newNode)) { - newNodes = newNodes.concat(newNode); - } - else { - newNodes.push(newNode); - } + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); } } - return newNodes; } codefix.createMissingMemberNodes = createMissingMemberNodes; - function createNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -77655,74 +78819,66 @@ var ts; case 149: case 150: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); - var property = ts.createProperty(undefined, modifiers, name, optional ? ts.createToken(55) : undefined, typeNode, undefined); - return property; + out(ts.createProperty(undefined, modifiers, name, optional ? ts.createToken(55) : undefined, typeNode, undefined)); + break; case 151: case 152: var signatures = checker.getSignaturesOfType(type, 0); if (!ts.some(signatures)) { - return undefined; + break; } if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody()); + break; } - var signatureDeclarations = []; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var signature = signatures_8[_i]; - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + outputMethod(signature, modifiers, name, createStubbedMethodBody()); } else { ts.Debug.assert(declarations.length === signatures.length); - var methodImplementingSignatures = createMethodImplementingSignatures(signatures, name, optional, modifiers); - signatureDeclarations.push(methodImplementingSignatures); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); } - return signatureDeclarations; - default: - return undefined; + break; } - function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); - if (signatureDeclaration) { - signatureDeclaration.decorators = undefined; - signatureDeclaration.modifiers = modifiers; - signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55) : undefined; - signatureDeclaration.body = body; - } - return signatureDeclaration; + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); } } - function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { - var parameters = createDummyParameters(callExpression.arguments.length, undefined, undefined, includeTypeScriptSyntax); - var typeParameters; - if (includeTypeScriptSyntax) { - var typeArgCount = ts.length(callExpression.typeArguments); - for (var i = 0; i < typeArgCount; i++) { - var name = typeArgCount < 8 ? String.fromCharCode(84 + i) : "T" + i; - var typeParameter = ts.createTypeParameterDeclaration(name, undefined, undefined); - (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); - } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152, enclosingDeclaration, 256); + if (!signatureDeclaration) { + return undefined; } - var newMethod = ts.createMethod(undefined, makeStatic ? [ts.createToken(115)] : undefined, undefined, methodName, undefined, typeParameters, parameters, includeTypeScriptSyntax ? ts.createKeywordTypeNode(119) : undefined, createStubbedMethodBody()); - return newMethod; + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(55) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); + } + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + var typeArguments = _a.typeArguments, args = _a.arguments; + return ts.createMethod(undefined, makeStatic ? [ts.createToken(115)] : undefined, undefined, methodName, undefined, inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 + typeArguments.length - 1 <= 90 ? String.fromCharCode(84 + i) : "T" + i); + }), createDummyParameters(args.length, undefined, undefined, inJs), inJs ? undefined : ts.createKeywordTypeNode(119), createStubbedMethodBody()); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; - function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + function createDummyParameters(argCount, names, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { - var newParameter = ts.createParameter(undefined, undefined, undefined, names && names[i] || "arg" + i, minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55) : undefined, addAnyType ? ts.createKeywordTypeNode(119) : undefined, undefined); + var newParameter = ts.createParameter(undefined, undefined, undefined, names && names[i] || "arg" + i, minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55) : undefined, inJs ? undefined : ts.createKeywordTypeNode(119), undefined); parameters.push(newParameter); } return parameters; @@ -77743,7 +78899,7 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, true); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, false); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119)); var restParameter = ts.createParameter(undefined, undefined, ts.createToken(24), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", maxNonRestArgs >= minArgumentCount ? ts.createToken(55) : undefined, anyArrayType, undefined); @@ -77754,7 +78910,6 @@ var ts; function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { return ts.createMethod(undefined, modifiers, undefined, name, optional ? ts.createToken(55) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } - codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), undefined, [ts.createLiteral("Method not implemented.")]))], true); } @@ -77773,217 +78928,227 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ], - getCodeActions: getActionsForAddExplicitTypeAnnotation + errorCodes: errorCodes, + getCodeActions: function (_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + if (ts.isSourceFileJavaScript(sourceFile)) { + return undefined; + } + var token = ts.getTokenAtPosition(sourceFile, start, false); + var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); + if (!fix) + return undefined; + var declaration = fix.declaration, textChanges = fix.textChanges; + var name = ts.getNameOfDeclaration(declaration); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); + return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var seenFunctions = ts.createMap(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, false), err.code, program, cancellationToken, seenFunctions); + if (fix) + changes.push.apply(changes, fix.textChanges); + }); + }, }); - function getActionsForAddExplicitTypeAnnotation(_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; - var token = ts.getTokenAtPosition(sourceFile, start, false); - var writer; - if (ts.isInJavaScriptFile(token)) { - return undefined; - } - switch (token.kind) { - case 71: - case 24: - case 114: - case 112: - case 113: - case 131: - break; + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; default: - return undefined; + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!isAllowedTokenKind(token.kind)) { + return undefined; } - var containingFunction = ts.getContainingFunction(token); - var checker = program.getTypeChecker(); switch (errorCode) { case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - return getCodeActionForVariableDeclaration(token.parent); - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: - return getCodeActionForVariableUsage(token); + return getCodeActionForVariableDeclaration(token.parent, sourceFile, program, cancellationToken); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, sourceFile, program, cancellationToken); + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction); + return getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken); } case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return getCodeActionForParameters(token.parent); + return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) + ? getCodeActionForParameters(token.parent, containingFunction, sourceFile, program, cancellationToken) + : undefined; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; - } - return undefined; - function getCodeActionForVariableDeclaration(declaration) { - if (!ts.isIdentifier(declaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(declaration.name); - var typeString = type && typeToString(type, declaration); - if (!typeString) { - return undefined; - } - return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); - } - function getCodeActionForVariableUsage(token) { - var symbol = checker.getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 229: - case 152: - case 153: - return true; - case 187: - return !!declaration.name; - } - return false; + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; + default: + throw ts.Debug.fail(String(errorCode)); } - function getCodeActionForParameters(parameterDeclaration) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; - } - var types = inferTypeForParametersFromUsage(containingFunction) || - ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); - if (!types) { - return undefined; - } - var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (type && !parameter.type && !parameter.initializer) { - var typeString = typeToString(type, containingFunction); - return typeString ? { - span: { start: parameter.end, length: 0 }, - newText: ": " + typeString - } : undefined; - } - }).filter(function (c) { return !!c; }); - return textChanges.length ? [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: textChanges - }] - }] : undefined; - } - function getCodeActionForSetAccessor(setAccessorDeclaration) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || - inferTypeForVariableFromUsage(setAccessorParameter.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function isAllowedTokenKind(kind) { + switch (kind) { + case 71: + case 24: + case 114: + case 112: + case 113: + case 131: + return true; + default: + return false; } - function getCodeActionForGetAccessor(getAccessorDeclaration) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20); - return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function getCodeActionForVariableDeclaration(declaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(declaration.name)) + return undefined; + var type = inferTypeForVariableFromUsage(declaration.name, sourceFile, program, cancellationToken); + return makeFix(declaration, declaration.name.getEnd(), type, program); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229: + case 152: + case 153: + return true; + case 187: + return !!declaration.name; } - function createCodeActions(name, start, typeString) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: start, length: 0 }, - newText: typeString - }] - }] - }]; + return false; + } + function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; } - function getReferences(token) { - var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); - ts.Debug.assert(!!references, "Found no references!"); - ts.Debug.assert(references.length === 1, "Found more references than expected"); - return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, false); }); + var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, sourceFile, program, cancellationToken) : undefined; }); + if (!types) + return undefined; + if (containingFunction.parameters.length !== types.length) { + return undefined; } - function inferTypeForVariableFromUsage(token) { - return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { + var parameter = _a[0], type = _a[1]; + return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; + })); + return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration, sourceFile, program, cancellationToken) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; } - function inferTypeForParametersFromUsage(containingFunction) { - switch (containingFunction.kind) { - case 153: - case 187: - case 229: - case 152: - var isConstructor = containingFunction.kind === 153; - var searchToken = isConstructor ? - getFirstChildOfKind(containingFunction, sourceFile, 123) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); - } - } - } - function getTypeAccessiblityWriter() { - if (!writer) { - var str_1 = ""; - var typeIsAccessible_1 = true; - var writeText = function (text) { return str_1 += text; }; - writer = { - string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, false).accessibility !== 0) { - typeIsAccessible_1 = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } - }; - } - writer.clear(); - return writer; + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, sourceFile, program, cancellationToken) || + inferTypeForVariableFromUsage(setAccessorParameter.name, sourceFile, program, cancellationToken); + return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); + } + function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; } - function typeToString(type, enclosingDeclaration) { - var writer = getTypeAccessiblityWriter(); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, sourceFile, program, cancellationToken); + var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20, sourceFile); + return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + } + function makeFix(declaration, start, type, program) { + return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; + } + function makeChange(declaration, start, type, program) { + var typeString = type && typeToString(type, declaration, program.getTypeChecker()); + return typeString === undefined ? undefined : { span: ts.createTextSpan(start, 0), newText: ": " + typeString }; + } + function getReferences(token, sourceFile, program, cancellationToken) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), sourceFile, token.getStart(sourceFile)); + if (!references || references.length !== 1) { + return []; } - function getFirstChildOfKind(node, sourcefile, kind) { - for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { - var child = _a[_i]; - if (child.kind === kind) - return child; - } - return undefined; + return references[0].references.map(function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, false); }); + } + function inferTypeForVariableFromUsage(token, sourceFile, program, cancellationToken) { + return InferFromReference.inferTypeFromReferences(getReferences(token, sourceFile, program, cancellationToken), program.getTypeChecker(), cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + switch (containingFunction.kind) { + case 153: + case 187: + case 229: + case 152: + var isConstructor = containingFunction.kind === 153; + var searchToken = isConstructor ? + ts.findChildOfKind(containingFunction, 123, sourceFile) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, sourceFile, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); + } } } + function getTypeAccessiblityWriter(checker) { + var str = ""; + var typeIsAccessible = true; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return typeIsAccessible ? str : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + writeLine: function () { return writeText(" "); }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str = ""; typeIsAccessible = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, false).accessibility !== 0) { + typeIsAccessible = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } + }; + } + function typeToString(type, enclosingDeclaration, checker) { + var writer = getTypeAccessiblityWriter(checker); + checker.writeType(type, enclosingDeclaration, undefined, writer); + return writer.getText(); + } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -77997,6 +79162,9 @@ var ts; } InferFromReference.inferTypeFromReferences = inferTypeFromReferences; function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (references.length === 0) { + return undefined; + } if (declaration.parameters) { var usageContext = {}; for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { @@ -78023,7 +79191,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2)); paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; } } @@ -78223,12 +79391,12 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), true)); + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, false, checker); var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, true) : checker.getAnyType()); + return checker.createPromiseType(types.length ? checker.getUnionType(types, 2) : checker.getAnyType()); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, false, checker)); @@ -78286,7 +79454,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2)); return isRestParameter ? checker.createArrayType(type) : type; } return undefined; @@ -78313,19 +79481,92 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false).parent; + if (!ts.isImportDeclaration(node)) { + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + var replacement = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(namespace.name, undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + var replacement_1 = ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 : 183; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var refactor; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -78333,11 +79574,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -78541,15 +79782,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -78564,11 +79801,11 @@ var ts; if ((symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -78582,7 +79819,6 @@ var ts; } var sourceFile = context.file; var ctorSymbol = getConstructorSymbol(context); - var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 | 3))) { @@ -78612,7 +79848,7 @@ var ts; if (!newClassDeclaration) { return undefined; } - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { var deleteCallback = deletes_1[_i]; deleteCallback(); @@ -78758,18 +79994,440 @@ var ts; })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: actionName, + description: description, + actions: [ + { + description: description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182: + return isAtTopLevelRequire(node); + case 180: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 && varStatement.parent.kind === 269; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, undefined, moduleSpecifier.text)); + break; + } + case 182: { + var call = parent; + if (ts.isRequireCall(call, false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455, true))) { + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211: { + var expression = statement.expression; + switch (expression.kind) { + case 182: { + if (ts.isRequireCall(expression, true)) { + changes.replaceNode(sourceFile, statement, makeImport(undefined, undefined, expression.arguments[0].text)); + } + return false; + } + case 195: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175: + case 176: { + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71: + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154: + case 155: + case 266: + case 267: + return undefined; + case 265: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + var newNodes = [ + makeConst(undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84), ts.createToken(79)]; + switch (exported.kind) { + case 187: + case 188: { + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200: { + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182: + if (ts.isRequireCall(exported, true)) { + return convertReExportAll(exported.arguments[0], checker); + } + default: + return [[ts.createExportAssignment(undefined, undefined, false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84)]; + switch (exported.kind) { + case 187: + case 188: + return functionExpressionToDeclaration(name, modifiers, exported); + case 200: + return classExpressionToDeclaration(name, modifiers, exported); + default: + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 175: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(undefined, importSpecifiers, moduleSpecifier)]; + } + } + case 176: { + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier), + makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + var namedBindingsNames = ts.createMap(); + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180: + return parent.name !== node; + case 177: + return parent.propertyName !== node; + default: + return true; + } + } + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier) + : makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, undefined, init)], 2)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration(undefined, undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); function getAvailableActions(context) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; @@ -78812,21 +80470,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; @@ -78844,7 +80502,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; var Messages; (function (Messages) { function createMessage(message) { @@ -78872,7 +80530,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -78915,6 +80573,9 @@ var ts; break; } } + if (!statements.length) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } if (ts.isReturnStatement(start) && !start.expression) { @@ -79119,7 +80780,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -79237,11 +80898,10 @@ var ts; case 153: return "constructor"; case 187: - return scope.name - ? "function expression '" + scope.name.text + "'" - : "anonymous function expression"; case 229: - return "function '" + scope.name.text + "'"; + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; case 188: return "arrow function"; case 152: @@ -79292,7 +80952,7 @@ var ts; if (!isJS) { var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1); } var paramDecl = ts.createParameter(undefined, undefined, undefined, name, undefined, typeNode); parameters.push(paramDecl); @@ -79311,7 +80971,7 @@ var ts; : undefined; if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -79333,13 +80993,10 @@ var ts; var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, true); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { - prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, - suffix: context.newLineCharacter - }); + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } var newNodes = []; var called = getCalledExpression(scope, range, functionNameText); @@ -79365,7 +81022,7 @@ var ts; for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { var variableDeclaration = exposedVariableDeclarations_1[_i]; bindingElements.push(ts.createBindingElement(undefined, undefined, ts.getSynthesizedDeepClone(variableDeclaration.name))); - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1); typeElements.push(ts.createPropertySignature(undefined, variableDeclaration.symbol.name, undefined, variableType, undefined)); sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; @@ -79420,10 +81077,12 @@ var ts; newNodes.push(call); } } - var replacementRange = isReadonlyArray(range.range) - ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } - : { pos: range.range.getStart(), end: range.range.end }; - changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; @@ -79449,9 +81108,9 @@ var ts; var file = scope.getSourceFile(); var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); var isJS = ts.isInJavaScriptFile(scope); - var variableType = isJS + var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -79469,14 +81128,14 @@ var ts; : ts.createThis(), ts.createIdentifier(localNameText)); var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, true); changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); if (oldVariableDeclaration) { - changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); var localReference = ts.createIdentifier(localNameText); changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } @@ -79488,14 +81147,10 @@ var ts; var newVariableStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2)); var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); if (nodeToInsertBefore.pos === 0) { - var insertionPos = ts.getSourceFileImportLocation(file); - changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { - prefix: insertionPos === 0 ? undefined : context.newLineCharacter, - suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter - }); + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, false); } else { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, false); } if (node.parent.kind === 211) { changeTracker.deleteRange(context.file, { pos: node.parent.getStart(), end: node.parent.end }); @@ -79959,7 +81614,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, false); if (resolvedSymbol === symbol) { continue; } @@ -80080,15 +81735,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { return undefined; @@ -80096,8 +81747,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -80148,13 +81799,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -80171,11 +81817,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -80723,9 +82369,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = ts.getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145) { var expr = name.expression; @@ -80985,8 +82631,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -81122,7 +82767,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -81131,10 +82776,11 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); }, @@ -81226,13 +82872,13 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -81554,13 +83200,19 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function getCombinedCodeFix(scope, fixId, formatOptions) { + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); @@ -81674,7 +83326,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -81731,6 +83382,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -81770,28 +83422,15 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257: - case 259: - case 265: - case 266: - case 152: - case 154: - case 155: - return true; - } - return false; - } function getContainingObjectLiteralElement(node) { switch (node.kind) { case 9: case 8: if (node.parent.kind === 145) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } case 71: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 || node.parent.parent.kind === 258) && node.parent.name === node ? node.parent : undefined; } @@ -81807,20 +83446,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_9 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_7.push(symbol); } }); - return result_9; + return result_7; } if (symbol) { - result_9.push(symbol); - return result_9; + result_7.push(symbol); + return result_7; } } return undefined; @@ -82244,7 +83883,7 @@ var ts; LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = JSON.parse(options); + var localOptions = options === undefined ? undefined : JSON.parse(options); return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); }); }; @@ -82374,7 +84013,7 @@ var ts; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), true, true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), true, true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -82409,8 +84048,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); return { @@ -82560,17 +84198,6 @@ var ts; Msg["Info"] = "Info"; Msg["Perf"] = "Perf"; })(Msg = server.Msg || (server.Msg = {})); - function getProjectRootPath(project) { - switch (project.projectKind) { - case server.ProjectKind.Configured: - return ts.getDirectoryPath(project.getProjectName()); - case server.ProjectKind.Inferred: - return ""; - case server.ProjectKind.External: - var projectName = ts.normalizeSlashes(project.getProjectName()); - return ts.getDirectoryPath(projectName); - } - } function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), @@ -82578,7 +84205,7 @@ var ts; compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, - projectRootPath: getProjectRootPath(project), + projectRootPath: project.getCurrentDirectory(), cachePath: cachePath, kind: "discover" }; @@ -82872,6 +84499,7 @@ var ts; CommandTypes["Saveto"] = "saveto"; CommandTypes["SignatureHelp"] = "signatureHelp"; CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; + CommandTypes["Status"] = "status"; CommandTypes["TypeDefinition"] = "typeDefinition"; CommandTypes["ProjectInfo"] = "projectInfo"; CommandTypes["ReloadProjects"] = "reloadProjects"; @@ -82892,8 +84520,10 @@ var ts; CommandTypes["BreakpointStatement"] = "breakpointStatement"; CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; CommandTypes["GetCodeFixes"] = "getCodeFixes"; - CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; + CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix"; + CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; @@ -83064,7 +84694,7 @@ var ts; }()); server.TextStorage = TextStorage; function isDynamicFileName(fileName) { - return ts.getBaseFileName(fileName)[0] === "^"; + return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^"; } server.isDynamicFileName = isDynamicFileName; var ScriptInfo = (function () { @@ -83079,6 +84709,7 @@ var ts; this.textStorage = new TextStorage(host, fileName); if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); + this.realpath = this.path; } this.scriptKind = scriptKind ? scriptKind @@ -83112,6 +84743,25 @@ var ts; ScriptInfo.prototype.getSnapshot = function () { return this.textStorage.getSnapshot(); }; + ScriptInfo.prototype.ensureRealPath = function () { + if (this.realpath === undefined) { + this.realpath = this.path; + if (this.host.realpath) { + ts.Debug.assert(!!this.containingProjects.length); + var project = this.containingProjects[0]; + var realpath = this.host.realpath(this.path); + if (realpath) { + this.realpath = project.toPath(realpath); + if (this.realpath !== this.path) { + project.projectService.realpathToScriptInfos.add(this.realpath, this); + } + } + } + } + }; + ScriptInfo.prototype.getRealpathIfDifferent = function () { + return this.realpath && this.realpath !== this.path ? this.realpath : undefined; + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatCodeSettings; }; @@ -83119,6 +84769,9 @@ var ts; var isNew = !this.isAttached(project); if (isNew) { this.containingProjects.push(project); + if (!project.getCompilerOptions().preserveSymlinks) { + this.ensureRealPath(); + } } return isNew; }; @@ -83156,7 +84809,7 @@ var ts; for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; if (p.projectKind === server.ProjectKind.Configured) { - p.directoryStructureHost.addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); } var isInfoRoot = p.isRoot(this); p.removeFile(this, false, false); @@ -83204,8 +84857,7 @@ var ts; return this.textStorage.getVersion(); }; ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.textStorage.getSnapshot(); - this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot())); }; ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { ts.Debug.assert(!this.isDynamicOrHasMixedContent()); @@ -83258,6 +84910,168 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + if (!host.directoryExists) { + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; var ConfigFileProgramReloadLevel; (function (ConfigFileProgramReloadLevel) { ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; @@ -83294,6 +85108,13 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -83371,7 +85192,7 @@ var ts; var ts; (function (ts) { ts.maxNumberOfFilesToIterateForInvalidation = 256; - function createResolutionCache(resolutionHost, rootDirForResolution) { + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; @@ -83380,6 +85201,7 @@ var ts; var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); @@ -83429,8 +85251,8 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } - function createHasInvalidatedResolution() { - if (allFilesHaveInvalidatedResolution) { + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { filesWithInvalidatedResolutions = undefined; return ts.returnTrue; } @@ -83541,8 +85363,8 @@ var ts; function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, undefined, false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); @@ -83663,8 +85485,8 @@ var ts; function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } if (!allFilesHaveInvalidatedResolution && dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { @@ -83742,6 +85564,9 @@ var ts; if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { return false; } + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } } @@ -83756,8 +85581,8 @@ var ts; function createTypeRootsWatch(_typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } resolutionHost.onChangedAutomaticTypeDirectiveNames(); }, 1); @@ -83903,6 +85728,243 @@ var ts; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +(function (ts) { + var BuilderState; + (function (BuilderState) { + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + function getAllDependencies(state, programOfThisState, sourceFile) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + var seenFileNamesMap = ts.createMap(); + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var server; (function (server) { @@ -83992,15 +86054,16 @@ var ts; this.documentRegistry = documentRegistry; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; - this.directoryStructureHost = directoryStructureHost; this.rootFiles = []; this.rootFilesMap = ts.createMap(); + this.plugins = []; this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); this.languageServiceEnabled = true; this.lastReportedVersion = 0; this.projectStructureVersion = 0; this.projectStateVersion = 0; this.hasChangedAutomaticTypeDirectiveNames = false; + this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { @@ -84019,7 +86082,7 @@ var ts; if (host.realpath) { this.realpath = function (path) { return host.realpath(path); }; } - this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, true); this.languageService = ts.createLanguageService(this, this.documentRegistry); if (!languageServiceEnabled) { this.disableLanguageService(); @@ -84068,7 +86131,7 @@ var ts; return this.getCompilationSettings(); }; Project.prototype.getNewLine = function () { - return this.directoryStructureHost.newLine; + return this.projectService.host.newLine; }; Project.prototype.getProjectVersion = function () { return this.projectStateVersion.toString(); @@ -84123,20 +86186,20 @@ var ts; return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); }; Project.prototype.useCaseSensitiveFileNames = function () { - return this.directoryStructureHost.useCaseSensitiveFileNames; + return this.projectService.host.useCaseSensitiveFileNames; }; Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }; Project.prototype.readFile = function (fileName) { - return this.directoryStructureHost.readFile(fileName); + return this.projectService.host.readFile(fileName); }; Project.prototype.fileExists = function (file) { var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); }; Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, true); + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }; Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); @@ -84147,6 +86210,9 @@ var ts; Project.prototype.getDirectories = function (path) { return this.directoryStructureHost.getDirectories(path); }; + Project.prototype.getCachedDirectoryStructureHost = function () { + return undefined; + }; Project.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); }; @@ -84187,15 +86253,6 @@ var ts; } return this.languageService; }; - Project.prototype.ensureBuilder = function () { - var _this = this; - if (!this.builder) { - this.builder = ts.createBuilder({ - getCanonicalFileName: this.projectService.toCanonicalFileName, - computeHash: function (data) { return _this.projectService.host.createHash(data); } - }); - } - }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -84205,8 +86262,8 @@ var ts; return []; } this.updateGraph(); - this.ensureBuilder(); - return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; Project.prototype.emitFile = function (scriptInfo, writeFile) { if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { @@ -84235,14 +86292,34 @@ var ts; } this.languageService.cleanupSemanticCache(); this.languageServiceEnabled = false; + this.builderState = undefined; this.resolutionCache.closeTypeRootsWatch(); this.projectService.onUpdateLanguageServiceStateForProject(this, false); }; Project.prototype.getProjectName = function () { return this.projectName; }; + Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) { + if (!newTypeAcquisition || !newTypeAcquisition.include) { + return newTypeAcquisition; + } + return __assign({}, newTypeAcquisition, { include: this.removeExistingTypings(newTypeAcquisition.include) }); + }; Project.prototype.getExternalFiles = function () { - return server.emptyArray; + var _this = this; + return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.getExternalFiles !== "function") + return; + try { + return plugin.getExternalFiles(_this); + } + catch (e) { + _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + if (e.stack) { + _this.projectService.logger.info(e.stack); + } + } + })); }; Project.prototype.getSourceFile = function (path) { if (!this.program) { @@ -84267,7 +86344,7 @@ var ts; this.rootFilesMap = undefined; this.externalFiles = undefined; this.program = undefined; - this.builder = undefined; + this.builderState = undefined; this.resolutionCache.clear(); this.resolutionCache = undefined; this.cachedUnresolvedImportsPerFile = undefined; @@ -84417,7 +86494,7 @@ var ts; Project.prototype.markAsDirty = function () { this.projectStateVersion++; }; - Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, result) { + Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, result, ambientModules) { var cached = this.cachedUnresolvedImportsPerFile.get(file.path); if (cached) { for (var _i = 0, cached_2 = cached; _i < cached_2.length; _i++) { @@ -84429,7 +86506,7 @@ var ts; var unresolvedImports; if (file.resolvedModules) { file.resolvedModules.forEach(function (resolvedModule, name) { - if (!resolvedModule && !ts.isExternalModuleNameRelative(name)) { + if (!resolvedModule && !ts.isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { var trimmed = name.trim(); var i = trimmed.indexOf("/"); if (i !== -1 && trimmed.charCodeAt(0) === 64) { @@ -84444,6 +86521,9 @@ var ts; }); } this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); + function isAmbientlyDeclaredModule(name) { + return ambientModules.some(function (m) { return m === name; }); + } }; Project.prototype.updateGraph = function () { this.resolutionCache.startRecordingFilesWithChangedResolutions(); @@ -84456,9 +86536,10 @@ var ts; if (this.languageServiceEnabled) { if (hasChanges || changedFiles.length) { var result = []; + var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { var sourceFile = _b[_a]; - this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + this.extractUnresolvedImportsFromSourceFile(sourceFile, result, ambientModules); } this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); } @@ -84466,21 +86547,22 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } - if (this.builder) { - this.builder.updateProgram(this.program); - } } else { this.lastCachedUnresolvedImportsList = undefined; - if (this.builder) { - this.builder.clear(); - } } if (hasChanges) { this.projectStructureVersion++; } return !hasChanges; }; + Project.prototype.getCurrentProgram = function () { + return this.program; + }; + Project.prototype.removeExistingTypings = function (include) { + var existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + return include.filter(function (i) { return existing.indexOf(i) < 0; }); + }; Project.prototype.setTypings = function (typings) { if (ts.arrayIsEqualTo(this.typingFiles, typings)) { return false; @@ -84537,7 +86619,7 @@ var ts; var _this = this; var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { if (_this.projectKind === ProjectKind.Configured) { - _this.directoryStructureHost.addOrDeleteFile(fileName, missingFilePath, eventKind); + _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); } if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { _this.missingFilesMap.delete(missingFilePath); @@ -84638,6 +86720,76 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; + Project.prototype.enableGlobalPlugins = function () { + var host = this.projectService.host; + var options = this.getCompilationSettings(); + if (!host.require) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.globalPlugins) { + var _loop_11 = function (globalPluginName) { + if (!globalPluginName) + return "continue"; + if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) + return "continue"; + this_1.projectService.logger.info("Loading global plugin " + globalPluginName); + this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + }; + var this_1 = this; + for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { + var globalPluginName = _a[_i]; + _loop_11(globalPluginName); + } + } + }; + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { + var _this = this; + this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + var log = function (message) { + _this.projectService.logger.info(message); + }; + for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) { + var searchPath = searchPaths_1[_i]; + var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); + if (resolvedModule) { + this.enableProxy(resolvedModule, pluginConfigEntry); + return; + } + } + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + }; + Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { + try { + if (typeof pluginModuleFactory !== "function") { + this.projectService.logger.info("Skipped loading plugin " + configEntry.name + " because it did expose a proper factory function"); + return; + } + var info = { + config: configEntry, + project: this, + languageService: this.languageService, + languageServiceHost: this, + serverHost: this.projectService.host + }; + var pluginModule = pluginModuleFactory({ typescript: ts }); + var newLS = pluginModule.create(info); + for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { + var k = _a[_i]; + if (!(k in newLS)) { + this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); + newLS[k] = this.languageService[k]; + } + } + this.projectService.logger.info("Plugin validation succeded"); + this.languageService = newLS; + this.plugins.push(pluginModule); + } + catch (e) { + this.projectService.logger.info("Plugin activation failed: " + e); + } + }; return Project; }()); server.Project = Project; @@ -84647,6 +86799,7 @@ var ts; var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, true, compilerOptions, false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); + _this.enableGlobalPlugins(); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -84718,7 +86871,6 @@ var ts; function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, cachedDirectoryStructureHost) { 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.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); _this.enablePlugins(); @@ -84762,67 +86914,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - if (this.projectService.globalPlugins) { - var _loop_11 = function (globalPluginName) { - if (!globalPluginName) - return "continue"; - if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) - return "continue"; - this_1.projectService.logger.info("Loading global plugin " + globalPluginName); - this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); - }; - var this_1 = this; - for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { - var globalPluginName = _c[_b]; - _loop_11(globalPluginName); - } - } - }; - ConfiguredProject.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { - var _this = this; - this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); - var log = function (message) { - _this.projectService.logger.info(message); - }; - for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) { - var searchPath = searchPaths_1[_i]; - var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); - if (resolvedModule) { - this.enableProxy(resolvedModule, pluginConfigEntry); - return; - } - } - this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); - }; - ConfiguredProject.prototype.enableProxy = function (pluginModuleFactory, configEntry) { - try { - if (typeof pluginModuleFactory !== "function") { - this.projectService.logger.info("Skipped loading plugin " + configEntry.name + " because it did expose a proper factory function"); - return; - } - var info = { - config: configEntry, - project: this, - languageService: this.languageService, - languageServiceHost: this, - serverHost: this.projectService.host - }; - var pluginModule = pluginModuleFactory({ typescript: ts }); - var newLS = pluginModule.create(info); - for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { - var k = _a[_i]; - if (!(k in newLS)) { - this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); - newLS[k] = this.languageService[k]; - } - } - this.projectService.logger.info("Plugin validation succeded"); - this.languageService = newLS; - this.plugins.push(pluginModule); - } - catch (e) { - this.projectService.logger.info("Plugin activation failed: " + e); - } + this.enableGlobalPlugins(); }; ConfiguredProject.prototype.getGlobalProjectErrors = function () { return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; @@ -84834,27 +86926,11 @@ var ts; this.projectErrors = projectErrors; }; ConfiguredProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { - this.typeAcquisition = newTypeAcquisition; + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); }; ConfiguredProject.prototype.getTypeAcquisition = function () { return this.typeAcquisition; }; - ConfiguredProject.prototype.getExternalFiles = function () { - var _this = this; - return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { - if (typeof plugin.getExternalFiles !== "function") - return; - try { - return plugin.getExternalFiles(_this); - } - catch (e) { - _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); - if (e.stack) { - _this.projectService.logger.info(e.stack); - } - } - })); - }; ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { var _this = this; ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); @@ -84929,7 +87005,7 @@ var ts; ts.Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined"); ts.Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined"); ts.Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined"); - this.typeAcquisition = newTypeAcquisition; + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); }; return ExternalProject; }(Project)); @@ -85027,13 +87103,6 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; - function combineProjectOutput(projects, action, comparer, areEqual) { - var outputs = ts.flatMap(projects, action); - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); - } - server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -85117,6 +87186,9 @@ var ts; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + if (this.host.realpath) { + this.realpathToScriptInfos = ts.createMultiMap(); + } this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); @@ -85215,9 +87287,11 @@ var ts; } switch (response.kind) { case server.ActionSet: + project.resolutionCache.clear(); this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings); break; case server.ActionInvalidate: + project.resolutionCache.clear(); this.typingsCache.deleteTypingsForProject(response.projectName); break; } @@ -85354,15 +87428,6 @@ var ts; this.refreshInferredProjects(); } }; - ProjectService.prototype.findContainingExternalProject = function (fileName) { - for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.containsFile(fileName)) { - return proj; - } - } - return undefined; - }; ProjectService.prototype.getFormatCodeOptions = function (file) { var formatCodeSettings; if (file) { @@ -85392,7 +87457,7 @@ var ts; else if (!info.isScriptOpen()) { if (info.containingProjects.length === 0) { this.stopWatchingScriptInfo(info); - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); } else { info.delayReloadNonMixedContentFile(); @@ -85403,7 +87468,7 @@ var ts; ProjectService.prototype.handleDeletedFile = function (info) { this.stopWatchingScriptInfo(info); if (!info.isScriptOpen()) { - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); this.delayUpdateProjectGraphs(containingProjects); @@ -85476,7 +87541,7 @@ var ts; ts.Debug.assert(info.isOrphan()); var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || - this.createInferredProject(ts.getDirectoryPath(info.path)); + this.createInferredProject(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path)); project.addRoot(info); project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { @@ -85546,10 +87611,17 @@ var ts; this.filenameToScriptInfo.forEach(function (info) { if (!info.isScriptOpen() && info.isOrphan()) { _this.stopWatchingScriptInfo(info); - _this.filenameToScriptInfo.delete(info.path); + _this.deleteScriptInfo(info); } }); }; + ProjectService.prototype.deleteScriptInfo = function (info) { + this.filenameToScriptInfo.delete(info.path); + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + this.realpathToScriptInfos.remove(realpath, info); + } + }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { @@ -85881,7 +87953,7 @@ var ts; }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); var languageServiceEnabled = !this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); @@ -85990,7 +88062,7 @@ var ts; }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { - if (!this.useInferredProjectPerProjectRoot) { + if (info.isDynamic || !this.useInferredProjectPerProjectRoot) { return undefined; } if (projectRootPath) { @@ -86042,6 +88114,38 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; + ProjectService.prototype.getSymlinkedProjects = function (info) { + var projects; + if (this.realpathToScriptInfos) { + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + ts.forEach(this.realpathToScriptInfos.get(realpath), combineProjects); + } + ts.forEach(this.realpathToScriptInfos.get(info.path), combineProjects); + } + return projects; + function combineProjects(toAddInfo) { + if (toAddInfo !== info) { + var _loop_12 = function (project) { + if (project.languageServiceEnabled && + !project.getCompilerOptions().preserveSymlinks && + !ts.contains(info.containingProjects, project)) { + if (!projects) { + projects = ts.createMultiMap(); + projects.add(toAddInfo.path, project); + } + else if (!ts.forEachEntry(projects, function (projs, path) { return path === toAddInfo.path ? false : ts.contains(projs, project); })) { + projects.add(toAddInfo.path, project); + } + } + }; + for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + _loop_12(project); + } + } + } + }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.fileWatcher); @@ -86066,13 +88170,15 @@ var ts; return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); }; ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + var _this = this; ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); var info = this.getScriptInfoForPath(path); if (!info) { - ts.Debug.assert(ts.isRootedDiskPath(fileName) || openedByClient, "Script info with relative file name can only be open script info"); - ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); var isDynamic = server.isDynamicFileName(fileName); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info"; }); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; } @@ -86207,13 +88313,23 @@ var ts; ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; + ProjectService.prototype.findExternalProjetContainingOpenScriptInfo = function (info) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.updateGraph(); + if (proj.containsScriptInfo(info)) { + return proj; + } + } + return undefined; + }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { var _this = this; var configFileName; var sendConfigFileDiagEvent = false; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); - var project = this.findContainingExternalProject(fileName); + var project = this.findExternalProjetContainingOpenScriptInfo(info); if (!project) { configFileName = this.getConfigFileNameForFile(info, projectRootPath); if (configFileName) { @@ -86222,6 +88338,9 @@ var ts; project = this.createConfiguredProject(configFileName); sendConfigFileDiagEvent = true; } + else { + project.updateGraph(); + } } } if (project && !project.languageServiceEnabled) { @@ -86255,13 +88374,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_12 = function (proj) { + var _loop_13 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_12(proj); + _loop_13(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -86382,7 +88501,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_13 = function (name) { + var _loop_14 = function (name) { var rule = this_2.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -86397,7 +88516,7 @@ var ts; } } if (rule.exclude) { - var _loop_14 = function (exclude) { + var _loop_15 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -86420,7 +88539,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_14(exclude); + _loop_15(exclude); } } else { @@ -86435,11 +88554,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_13(name); + _loop_14(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_15 = function (i) { + var _loop_16 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -86473,7 +88592,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_15(i); + _loop_16(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -86746,11 +88865,30 @@ var ts; }; } server.toEvent = toEvent; + function isProjectsArray(projects) { + return !!projects.length; + } + function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + var outputs = ts.flatMap(isProjectsArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!isProjectsArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (projects, path) { + var value = getValue(path); + outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); + }); + } + return comparer + ? ts.sortAndDeduplicate(outputs, comparer, areEqual) + : ts.deduplicate(outputs, areEqual); + } var Session = (function () { function Session(opts) { var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, + _a[server.CommandNames.Status] = function () { + var response = { version: ts.version }; + return _this.requiredResponse(response); + }, _a[server.CommandNames.OpenExternalProject] = function (request) { _this.projectService.openExternalProject(request.arguments, false); return _this.requiredResponse(true); @@ -86996,9 +89134,14 @@ var ts; _a[server.CommandNames.GetCodeFixesFull] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); }, + _a[server.CommandNames.GetCombinedCodeFix] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, true)); + }, + _a[server.CommandNames.GetCombinedCodeFixFull] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, false)); + }, _a[server.CommandNames.ApplyCodeActionCommand] = function (request) { - _this.applyCodeActionCommand(request.command, request.seq, request.arguments); - return _this.notRequired(); + return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments)); }, _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); @@ -87434,6 +89577,7 @@ var ts; }; Session.prototype.getProjects = function (args) { var projects; + var symLinkedProjects; if (args.projectFileName) { var project = this.getProject(args.projectFileName); if (project) { @@ -87443,12 +89587,13 @@ var ts; else { var scriptInfo = this.projectService.getScriptInfo(args.file); projects = scriptInfo.containingProjects; + symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); - if (!projects || !projects.length) { + if ((!projects || !projects.length) && !symLinkedProjects) { return server.Errors.ThrowNoProject(); } - return projects; + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; }; Session.prototype.getDefaultProject = function (args) { if (args.projectFileName) { @@ -87461,6 +89606,7 @@ var ts; return info.getDefaultProject(); }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); @@ -87476,7 +89622,7 @@ var ts; locs: server.emptyArray }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); if (!renameLocations) { return server.emptyArray; @@ -87509,7 +89655,7 @@ var ts; return { info: renameInfo, locs: locs }; } else { - return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (p, file) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); } function renameLocationIsEqualTo(a, b) { if (a === b) { @@ -87543,6 +89689,7 @@ var ts; } }; Session.prototype.getReferences = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); @@ -87557,7 +89704,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { return server.emptyArray; @@ -87585,7 +89732,7 @@ var ts; }; } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, ts.equateValues); + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { return project.getLanguageService().findReferences(file, position); }, undefined, ts.equateValues); } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { @@ -87770,9 +89917,9 @@ var ts; if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); } @@ -87791,27 +89938,28 @@ var ts; return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source); }); return simplifiedResult - ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action, scriptInfo); }) })); }) + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(project, action); }) })); }) : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var _this = this; var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); if (!info) { return server.emptyArray; } - var result = []; - var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { - var project = projectsToSearch_1[_i]; + var projects = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + var symLinkedProjects = !args.projectFileName && this.projectService.getSymlinkedProjects(info); + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects, function (project, info) { + var result; if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.getCompilationSettings().noEmit) { - result.push({ + result = { projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out - }); + }; } - } - return result; + return result; + }); }; Session.prototype.emitFile = function (args) { var _this = this; @@ -87950,7 +90098,10 @@ var ts; var projects = this.getProjects(args); var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; if (simplifiedResult) { - return server.combineProjectOutput(projects, function (project) { + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); if (!navItems) { return server.emptyArray; @@ -87981,7 +90132,12 @@ var ts; }, undefined, areNavToItemsForTheSameLocation); } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } + return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + }, undefined, navigateToItemIsEqualTo); } function navigateToItemIsEqualTo(a, b) { if (a === b) { @@ -88038,7 +90194,6 @@ var ts; return project.getLanguageService().getApplicableRefactors(file, position || textRange); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { - var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; @@ -88053,15 +90208,9 @@ var ts; var mappedRenameLocation = void 0; if (renameFilename !== undefined && renameLocation !== undefined) { var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); - var snapshot = renameScriptInfo.getSnapshot(); - var oldText = snapshot.getText(0, snapshot.getLength()); - mappedRenameLocation = getLocationInNewDocument(oldText, renameFilename, renameLocation, edits); + mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } - return { - renameLocation: mappedRenameLocation, - renameFilename: renameFilename, - edits: edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) - }; + return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(project, edits) }; } else { return result; @@ -88081,25 +90230,33 @@ var ts; return undefined; } if (simplifiedResult) { - return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + return codeActions.map(function (codeAction) { return _this.mapCodeAction(project, codeAction); }); } else { return codeActions; } }; - Session.prototype.applyCodeActionCommand = function (commandName, requestSeq, args) { - var _this = this; + Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { + var scope = _a.scope, fixId = _a.fixId; + ts.Debug.assert(scope.type === "file"); + var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; + var formatOptions = this.projectService.getFormatCodeOptions(file); + var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, formatOptions); + if (simplifiedResult) { + return { changes: this.mapTextChangesToCodeEdits(project, res.changes), commands: res.commands }; + } + else { + return res; + } + }; + Session.prototype.applyCodeActionCommand = function (args) { var commands = args.command; - var _loop_16 = function (command) { - var project = this_4.getFileAndProject(command).project; - var output = function (success, message) { return _this.doOutput({}, commandName, requestSeq, success, message); }; - project.getLanguageService().applyCodeActionCommand(command).then(function (result) { output(true, result.successMessage); }, function (error) { output(false, error); }); - }; - var this_4 = this; for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - _loop_16(command); + var project = this.getFileAndProject(command).project; + project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); } + return {}; }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { var startPosition = undefined, endPosition = undefined; @@ -88119,18 +90276,18 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (_a, scriptInfo) { + Session.prototype.mapCodeAction = function (project, _a) { var _this = this; - 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 }; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId; + var changes = unmappedChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); + return { description: description, changes: changes, commands: commands, fixId: fixId }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; - var scriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(textChanges.fileName)); + return textChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); + }; + Session.prototype.mapTextChangesToCodeEditsUsingScriptinfo = function (textChanges, scriptInfo) { + var _this = this; return { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) @@ -88295,8 +90452,8 @@ var ts; continue; } for (var i = textChanges_3.length - 1; i >= 0; i--) { - var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_8 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_8); + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; @@ -88620,7 +90777,7 @@ var ts; return this.index.getText(rangeStart, rangeEnd - rangeStart); }; LineIndexSnapshot.prototype.getLength = function () { - return this.index.root.charCount(); + return this.index.getLength(); }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { @@ -89634,7 +91791,8 @@ var ts; } var logger = createLogger(); var sys = ts.sys; - var useWatchGuard = process.platform === "win32" && ts.getNodeMajorVersion() >= 4; + var nodeVersion = ts.getNodeMajorVersion(); + var useWatchGuard = process.platform === "win32" && nodeVersion >= 4; var originalWatchDirectory = sys.watchDirectory.bind(sys); var noopWatcher = { close: ts.noop }; function watchDirectorySwallowingException(path, callback, recursive) { @@ -89769,6 +91927,10 @@ var ts; pluginProbeLocations: pluginProbeLocations, allowLocalPluginLoads: allowLocalPluginLoads }; + logger.info("Starting TS Server"); + logger.info("Version: " + ts.version); + logger.info("Arguments: " + process.argv.join(" ")); + logger.info("Platform: " + os.platform() + " NodeVersion: " + nodeVersion + " CaseSensitive: " + sys.useCaseSensitiveFileNames); var ioSession = new IOSession(options); process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 6fd389d170a98..cd1b577b71173 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -453,6 +454,9 @@ declare namespace ts { interface JSDocContainer { } type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -604,15 +608,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends NamedDeclaration { - propertyName?: PropertyName; - dotDotDotToken?: DotDotDotToken; - name: DeclarationName; - questionToken?: QuestionToken; - exclamationToken?: ExclamationToken; - type?: TypeNode; - initializer?: Expression; - } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -643,7 +639,7 @@ declare namespace ts { body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -660,30 +656,30 @@ declare namespace ts { } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; + parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -881,7 +877,7 @@ declare namespace ts { type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; - type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; @@ -905,6 +901,7 @@ declare namespace ts { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; + name: never; } interface LiteralLikeNode extends Node { text: string; @@ -1279,7 +1276,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassDeclaration | ClassExpression; + parent?: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1366,6 +1363,7 @@ declare namespace ts { interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; parent?: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier?: Expression; @@ -1620,7 +1618,7 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. @@ -1731,6 +1729,16 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -1750,7 +1758,8 @@ declare namespace ts { getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; /** * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead * This will be removed in a future version. @@ -1790,33 +1799,79 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, SuppressAnyReturnType = 256, WriteTypeParametersInQualifiedName = 512, - AllowThisInObjectLiteral = 1024, - AllowQualifedNameInPlaceOfIdentifier = 2048, - AllowAnonymousIdentifier = 8192, - AllowEmptyUnionOrIntersection = 16384, - AllowEmptyTuple = 32768, - IgnoreErrors = 60416, - InObjectTypeLiteral = 1048576, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + IgnoreErrors = 3112960, + InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, + InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469295, + } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + } + /** + * @deprecated + */ interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; - buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - interface SymbolWriter { + /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; + /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + } + /** + * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString + */ + interface SymbolWriter extends SymbolTracker { writeKeyword(text: string): void; writeOperator(text: string): void; writePunctuation(text: string): void; @@ -1829,34 +1884,6 @@ declare namespace ts { increaseIndent(): void; decreaseIndent(): void; clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError(): void; - reportPrivateInBaseOfClassExpression(propertyName: string): void; - reportInaccessibleUniqueSymbolError(): void; - } - enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 4, - NoTruncation = 8, - WriteArrowStyleSignature = 16, - WriteOwnNameForAnyLike = 32, - WriteTypeArgumentsOfSignature = 64, - InElementType = 128, - UseFullyQualifiedType = 256, - InFirstTypeArgument = 512, - InTypeAlias = 1024, - SuppressAnyReturnType = 4096, - AddUndefined = 8192, - WriteClassExpressionAsTypeLiteral = 16384, - InArrayType = 32768, - UseAliasDefinedOutsideCurrentScope = 65536, - AllowUniqueESSymbolType = 131072, - } - enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, } enum TypePredicateKind { This = 0, @@ -2071,6 +2098,7 @@ declare namespace ts { EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, ContainsSpread = 1024, + ReverseMapped = 2048, ClassOrInterface = 3, } interface ObjectType extends Type { @@ -2150,15 +2178,14 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - Contravariant = 1, - NakedTypeVariable = 2, - MappedType = 4, - ReturnType = 8, - NeverType = 16, + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, } interface InferenceInfo { typeParameter: TypeParameter; candidates: Type[]; + contraCandidates: Type[]; inferredType: Type; priority: InferencePriority; topLevel: boolean; @@ -2299,6 +2326,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -2472,12 +2500,13 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; + createHash?(data: string): string; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2634,6 +2663,10 @@ declare namespace ts { * collisions. */ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -2689,6 +2722,13 @@ declare namespace ts { interface PrinterOptions { removeComments?: boolean; newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + } + interface SymbolTracker { + trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + reportInaccessibleThisError?(): void; + reportPrivateInBaseOfClassExpression?(propertyName: string): void; + reportInaccessibleUniqueSymbolError?(): void; } interface TextSpan { start: number; @@ -2701,6 +2741,71 @@ declare namespace ts { interface SyntaxList extends Node { _children: Node[]; } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + DelimitersMask = 28, + AllowTrailingComma = 32, + Indented = 64, + SpaceBetweenBraces = 128, + SpaceBetweenSiblings = 256, + Braces = 512, + Parenthesis = 1024, + AngleBrackets = 2048, + SquareBrackets = 4096, + BracketsMask = 7680, + OptionalIfUndefined = 8192, + OptionalIfEmpty = 16384, + Optional = 24576, + PreferNewLine = 32768, + NoTrailingNewLine = 65536, + NoInterveningComments = 131072, + NoSpaceIfEmpty = 262144, + SingleElement = 524288, + Modifiers = 131328, + HeritageClauses = 256, + SingleLineTypeLiteralMembers = 448, + MultiLineTypeLiteralMembers = 65, + TupleTypeElements = 336, + UnionTypeConstituents = 260, + IntersectionTypeConstituents = 264, + ObjectBindingPatternElements = 262576, + ArrayBindingPatternElements = 262448, + ObjectLiteralExpressionProperties = 263122, + ArrayLiteralExpressionElements = 4466, + CommaListElements = 272, + CallExpressionArguments = 1296, + NewExpressionArguments = 9488, + TemplateExpressionSpans = 131072, + SingleLineBlockStatements = 384, + MultiLineBlockStatements = 65, + VariableDeclarationList = 272, + SingleLineFunctionBodyStatements = 384, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 256, + ClassMembers = 65, + InterfaceMembers = 65, + EnumMembers = 81, + CaseBlockClauses = 65, + NamedImportsOrExportsElements = 432, + JsxElementOrFragmentChildren = 131072, + JsxElementAttributes = 131328, + CaseOrDefaultClauseStatements = 81985, + HeritageClauseTypes = 272, + SourceFileStatements = 65537, + Decorators = 24577, + TypeArguments = 26896, + TypeParameters = 26896, + Parameters = 1296, + IndexSignatureParameters = 4432, + } } declare namespace ts { const versionMajorMinor = "2.7"; @@ -2725,26 +2830,14 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - /** - * Partial interface of the System thats needed to support the caching of directory structure - */ - interface DirectoryStructureHost { + interface System { + args: string[]; newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - exit(exitCode?: number): void; - } - interface System extends DirectoryStructureHost { - args: string[]; getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2752,7 +2845,13 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2760,9 +2859,11 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; + exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; + clearScreen?(): void; } interface FileWatcher { close(): void; @@ -2915,7 +3016,7 @@ declare namespace ts { function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; - function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; @@ -3107,6 +3208,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; @@ -3129,7 +3231,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -3149,8 +3251,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; @@ -3288,13 +3392,13 @@ declare namespace ts { declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ - function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; - function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; + function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -3763,18 +3867,7 @@ declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } declare namespace ts { - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } -} -declare namespace ts { - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -3924,6 +4017,7 @@ declare namespace ts { useCaseSensitiveFileNames?(): boolean; readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; @@ -3982,7 +4076,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; 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[]; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -3998,8 +4093,13 @@ declare namespace ts { getProgram(): Program; dispose(): void; } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4074,6 +4174,17 @@ declare namespace ts { */ commands?: CodeActionCommand[]; } + interface CodeFixAction extends CodeAction { + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands: ReadonlyArray | undefined; + } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } @@ -4210,6 +4321,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4227,6 +4339,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4342,6 +4455,7 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: string; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -4508,6 +4622,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", + optionalModifier = "optional", } enum ClassificationTypeNames { comment = "comment", @@ -4653,9 +4768,6 @@ declare namespace ts { declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.7"; - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; @@ -4688,6 +4800,8 @@ declare namespace ts.server { }; }; interface ServerHost extends System { + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout(timeoutId: any): void; setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; @@ -4903,6 +5017,7 @@ declare namespace ts.server.protocol { Rename = "rename", Saveto = "saveto", SignatureHelp = "signatureHelp", + Status = "status", TypeDefinition = "typeDefinition", ProjectInfo = "projectInfo", ReloadProjects = "reloadProjects", @@ -4915,6 +5030,7 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", @@ -5004,6 +5120,21 @@ declare namespace ts.server.protocol { file: string; projectFileName?: string; } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } /** * Requests a JS Doc comment template for a given position */ @@ -5262,6 +5393,13 @@ declare namespace ts.server.protocol { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } + interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } interface ApplyCodeActionCommandRequest extends Request { command: CommandTypes.ApplyCodeActionCommand; arguments: ApplyCodeActionCommandRequestArgs; @@ -5293,7 +5431,15 @@ declare namespace ts.server.protocol { /** * Errorcodes we want to get the fixes for. */ - errorCodes?: number[]; + errorCodes?: ReadonlyArray; + } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; } interface ApplyCodeActionCommandRequestArgs { /** May also be an array of commands. */ @@ -6037,7 +6183,7 @@ declare namespace ts.server.protocol { } interface CodeFixResponse extends Response { /** The code actions that are available */ - body?: CodeAction[]; + body?: CodeFixAction[]; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -6047,6 +6193,17 @@ declare namespace ts.server.protocol { /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ commands?: {}[]; } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands?: ReadonlyArray<{}>; + } + interface CodeFixAction extends CodeAction { + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + } /** * Format and format on key response message. */ @@ -6088,6 +6245,11 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ includeExternalModuleExports: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + includeInsertTextCompletions: boolean; } /** * Completions request; value of command field is "completions". @@ -6156,6 +6318,12 @@ declare namespace ts.server.protocol { * is often the same as the name but may be different in certain circumstances. */ sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -6829,6 +6997,7 @@ declare namespace ts.server.protocol { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -7071,10 +7240,12 @@ declare namespace ts.server { private getApplicableRefactors(args); private getEditsForRefactor(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); - private applyCodeActionCommand(commandName, requestSeq, args); + private getCombinedCodeFix({scope, fixId}, simplifiedResult); + private applyCodeActionCommand(args); private getStartAndEndPosition(args, scriptInfo); - private mapCodeAction({description, changes: unmappedChanges, commands}, scriptInfo); + private mapCodeAction(project, {description, changes: unmappedChanges, commands, fixId}); private mapTextChangesToCodeEdits(project, textChanges); + private mapTextChangesToCodeEditsUsingScriptinfo(textChanges, scriptInfo); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); private getDiagnosticsForProject(next, delay, fileName); @@ -7113,6 +7284,7 @@ declare namespace ts.server { open(newText: string): void; close(fileExists?: boolean): void; getSnapshot(): IScriptSnapshot; + private ensureRealPath(); getFormatCodeSettings(): FormatCodeSettings; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; @@ -7166,6 +7338,17 @@ declare namespace ts.server { onProjectClosed(project: Project): void; } } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} declare namespace ts.server { enum ProjectKind { Inferred = 0, @@ -7209,19 +7392,19 @@ declare namespace ts.server { private documentRegistry; private compilerOptions; compileOnSaveEnabled: boolean; - directoryStructureHost: DirectoryStructureHost; private rootFiles; private rootFilesMap; private program; private externalFiles; private missingFilesMap; + private plugins; private cachedUnresolvedImportsPerFile; private lastCachedUnresolvedImportsList; protected languageService: LanguageService; languageServiceEnabled: boolean; readonly trace?: (s: string) => void; readonly realpath?: (path: string) => string; - private builder; + private builderState; /** * Set of files names that were updated since the last call to getChangesSinceVersion. */ @@ -7282,7 +7465,6 @@ declare namespace ts.server { getGlobalProjectErrors(): ReadonlyArray; getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; - private ensureBuilder(); private shouldEmitFile(scriptInfo); getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; /** @@ -7293,6 +7475,7 @@ declare namespace ts.server { disableLanguageService(): void; getProjectName(): string; abstract getTypeAcquisition(): TypeAcquisition; + protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile; close(): void; @@ -7313,12 +7496,12 @@ declare namespace ts.server { removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; registerFileUpdate(fileName: string): void; markAsDirty(): void; - private extractUnresolvedImportsFromSourceFile(file, result); /** * Updates set of files that contribute to this project * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph(): boolean; + protected removeExistingTypings(include: string[]): string[]; private setTypings(typings); private updateGraphWorker(); private detachScriptInfoFromProject(uncheckedFileName); @@ -7329,6 +7512,9 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; + protected enableGlobalPlugins(): void; + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + private enableProxy(pluginModuleFactory, configEntry); } /** * If a file is opened and no tsconfig (or jsconfig) is found, @@ -7357,7 +7543,6 @@ declare namespace ts.server { private typeAcquisition; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; - private plugins; /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; @@ -7368,8 +7553,6 @@ declare namespace ts.server { updateGraph(): boolean; getConfigFilePath(): NormalizedPath; enablePlugins(): void; - private enablePlugin(pluginConfigEntry, searchPaths); - private enableProxy(pluginModuleFactory, configEntry); /** * Get the errors that dont have any file name associated */ @@ -7381,7 +7564,6 @@ declare namespace ts.server { setProjectErrors(projectErrors: Diagnostic[]): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; getTypeAcquisition(): TypeAcquisition; - getExternalFiles(): SortedReadonlyArray; close(): void; getEffectiveTypeRoots(): string[]; } @@ -7484,10 +7666,6 @@ declare namespace ts.server { function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; - /** - * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. - */ - function combineProjectOutput(projects: ReadonlyArray, action: (project: Project) => ReadonlyArray, comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; hostInfo: string; @@ -7604,7 +7782,6 @@ declare namespace ts.server { * @param forceInferredProjectsRefresh when true updates the inferred projects even if there is no pending work to update the files/project structures */ private ensureProjectStructuresUptoDate(forceInferredProjectsRefresh?); - private findContainingExternalProject(fileName); getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; private updateProjectGraphs(projects); private onSourceFileChanged(fileName, eventKind); @@ -7623,6 +7800,7 @@ declare namespace ts.server { */ private closeOpenFile(info); private deleteOrphanScriptInfoNotInAnyProject(); + private deleteScriptInfo(info); private configFileExists(configFileName, canonicalConfigFilePath, info); private setConfigFileExistenceByNewConfiguredProject(project); /** @@ -7681,7 +7859,9 @@ declare namespace ts.server { getScriptInfo(uncheckedFileName: string): ScriptInfo; private watchClosedScriptInfo(info); private stopWatchingScriptInfo(info); - getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: DirectoryStructureHost): ScriptInfo; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { + fileExists(path: string): boolean; + }): ScriptInfo; private getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent?, scriptKind?, hasMixedContent?, hostToQueryFileExistsOn?); /** * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred @@ -7722,6 +7902,7 @@ declare namespace ts.server { * @param fileContent is a known version of the file content that is more up to date than the one on disk */ openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; + private findExternalProjetContainingOpenScriptInfo(info); openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; /** * Close file whose contents is managed by the client diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index a65ef12d20047..e879b3dd0685d 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -489,14 +489,19 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; (function (TokenFlags) { @@ -510,8 +515,9 @@ var ts; TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; - TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { @@ -556,47 +562,77 @@ var ts; // Diagnostics were produced and outputs were generated in spite of them. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // empty space NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; // Error handling - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; // State - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; // even though `T` can't be accessed in the current scope. - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -604,12 +640,14 @@ var ts; // Write symbols's type argument if it is instantiated symbol // eg. class C { p: T } <-- Show p as C.p here // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -745,6 +783,7 @@ var ts; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -871,6 +910,7 @@ var ts; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -894,11 +934,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1181,6 +1219,8 @@ var ts; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -1198,20 +1238,22 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; // Masks // - Additional bitmasks TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; @@ -1248,6 +1290,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1294,6 +1337,78 @@ var ts; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1396,7 +1511,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1409,6 +1524,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -1552,6 +1668,9 @@ var ts; ts.forEach = forEach; /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -1561,6 +1680,19 @@ var ts; return undefined; } ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1577,13 +1709,27 @@ var ts; ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { var result = []; - Debug.assert(arrayA.length === arrayB.length); + Debug.assertEqual(arrayA.length, arrayB.length); for (var i = 0; i < arrayA.length; i++) { result.push(callback(arrayA[i], arrayB[i], i)); } return result; } ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; function zipToMap(keys, values) { Debug.assert(keys.length === values.length); var map = createMap(); @@ -1666,17 +1812,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -1748,11 +1883,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1824,25 +1960,33 @@ var ts; return result; } ts.flatMap = flatMap; - function flatMapIter(iter, mapfn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapfn(value); - if (res) { - if (isArray(res)) { - result.push.apply(result, res); - } - else { - result.push(res); + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); } - } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; } - return result; } - ts.flatMapIter = flatMapIter; + ts.flatMapIterator = flatMapIterator; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1865,12 +2009,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -1879,20 +2034,35 @@ var ts; return result; } ts.mapDefined = mapDefined; - function mapDefinedIter(iter, mapFn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapFn(value); - if (res !== undefined) { - result.push(res); + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } } - } - return result; + }; } - ts.mapDefinedIter = mapDefinedIter; + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2158,7 +2328,7 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // Note: we need the following type assertion because of GH #17069 + // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2665,6 +2835,9 @@ var ts; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -3069,7 +3242,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */) + if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) return 3; } // Per RFC 1738 'file' URI schema has the shape file:/// @@ -3149,11 +3322,6 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ - function moduleHasNonRelativeName(moduleName) { - return !ts.isExternalModuleNameRelative(moduleName); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -3176,7 +3344,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3236,7 +3406,7 @@ var ts; ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part @@ -3266,7 +3436,7 @@ var ts; } else { // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" + // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + ts.directorySeparator]; @@ -3285,7 +3455,7 @@ var ts; var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } // Find the component that differs @@ -3507,7 +3677,6 @@ var ts; function getSubPatternFromSpec(spec, basePath, usage, _a) { var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; - var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); var lastComponent = lastOrUndefined(components); @@ -3524,11 +3693,7 @@ var ts; for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { var component = components_1[_i]; if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - return undefined; - } subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; } else { if (usage === "directories") { @@ -3854,10 +4019,10 @@ var ts; } function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0 /* None */; this.modifierFlagsCache = 0 /* None */; this.transformFlags = 0 /* None */; @@ -3997,9 +4162,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; /** @@ -4118,182 +4281,20 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - /** - * If the readDirectory result was already cached, it returns that - * Otherwise gets result from host and caches it. - * The host request is done under try catch block to avoid caching incorrect result - */ - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - // If there is exception to read directories, dont cache the result and direct the calls to host - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - // Just clear the cache for now - // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated - clearCache(); - } - else { - // This was earlier a file (hence not in cached directory contents) - // or we never cached the directory containing it - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - // Folder added or removed, clear the cache instead of updating the folder and its structure - clearCache(); - } - else { - // No need to update the directory structure, just files - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.singleElementArray = singleElementArray; })(ts || (ts = {})); /// var ts; @@ -4568,7 +4569,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -4601,6 +4602,9 @@ var ts; return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } var nodeSystem = { + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -4685,7 +4689,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -5022,6 +5031,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5136,6 +5147,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -5190,7 +5202,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -5278,6 +5290,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5356,6 +5369,10 @@ var ts; Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5442,7 +5459,6 @@ var ts; The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), @@ -5493,6 +5509,7 @@ var ts; Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), @@ -5533,7 +5550,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -5640,6 +5657,9 @@ var ts; Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5668,6 +5688,9 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5743,9 +5766,9 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -5757,14 +5780,18 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { - ts.emptyArray = []; + ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -5784,15 +5811,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str += " "; }, @@ -5806,10 +5842,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -5843,12 +5879,19 @@ var ts; return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -6069,7 +6112,7 @@ var ts; function getLiteralText(node, sourceFile) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent) { + if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; @@ -6509,7 +6552,7 @@ var ts; return node === parent.type; case 182 /* CallExpression */: case 183 /* NewExpression */: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -7095,11 +7138,6 @@ var ts; (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")'). - * This function does not test if the node is in a JavaScript file or not. - */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 182 /* CallExpression */) { return false; @@ -7258,41 +7296,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 /* ModuleDeclaration */ && node.body && node.body.kind === 234 /* ModuleDeclaration */ && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -7323,7 +7350,7 @@ var ts; if (node.kind === 147 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -7433,6 +7460,33 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208 /* Block */: + case 209 /* VariableStatement */: + case 221 /* WithStatement */: + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -7782,6 +7836,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; /** * Includes the word "Symbol" with unicode escapes */ @@ -8214,7 +8272,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -8409,7 +8479,7 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (node.type) { + if (ts.hasType(node)) { return node.type; } if (checkJSDoc || isInJavaScriptFile(node)) { @@ -8854,14 +8924,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -9224,6 +9294,10 @@ var ts; return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9430,8 +9504,8 @@ var ts; // // { // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; @@ -10082,7 +10156,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192 /* AwaitExpression */; + return node.kind === 190 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -10555,7 +10629,7 @@ var ts; /* @internal */ function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; // Keywords @@ -10669,6 +10743,18 @@ var ts; return node && (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */); } ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; // Type members function isTypeElement(node) { var kind = node.kind; @@ -11223,6 +11309,39 @@ var ts; return !!node.jsDoc && node.jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); /// /// @@ -11369,7 +11488,7 @@ var ts; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: - Can contain Unicode 3.0.0 categories: + Can contain Unicode 3.0.0 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -11377,7 +11496,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: = - Can contain IdentifierStart + Unicode 3.0.0 categories: + Can contain IdentifierStart + Unicode 3.0.0 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), or @@ -11391,7 +11510,7 @@ var ts; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers IdentifierStart :: - Can contain Unicode 6.2 categories: + Can contain Unicode 6.2 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -11399,7 +11518,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: - Can contain IdentifierStart + Unicode 6.2 categories: + Can contain IdentifierStart + Unicode 6.2 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), @@ -11718,7 +11837,7 @@ var ts; } function scanConflictMarkerTrivia(text, pos, error) { if (error) { - error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); } var ch = text.charCodeAt(pos); var len = text.length; @@ -11974,19 +12093,60 @@ var ts; lookAhead: lookAhead, scanRange: scanRange, }; - function error(message, length) { + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } if (onError) { + var oldPos = pos; + pos = errPos; onError(message, length || 0); + pos = oldPos; } } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } function scanNumber() { var start = pos; - while (isDigit(text.charCodeAt(pos))) - pos++; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; if (text.charCodeAt(pos) === 46 /* dot */) { pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; + decimalFragment = scanNumberFragment(); } var end = pos; if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { @@ -11994,17 +12154,29 @@ var ts; tokenFlags |= 16 /* Scientific */; if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) pos++; - if (isDigit(text.charCodeAt(pos))) { - pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; - end = pos; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); } else { - error(ts.Diagnostics.Digit_expected); + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; } } - return "" + +(text.substring(start, end)); + if (tokenFlags & 512 /* ContainsSeparator */) { + var result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + return "" + +result; + } + else { + return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + } } function scanOctalDigits() { var start = pos; @@ -12017,21 +12189,39 @@ var ts; * Scans the given number of hexadecimal digits in the text, * returning -1 if the given number is unavailable. */ - function scanExactNumberOfHexDigits(count) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); } /** * Scans as many hexadecimal digits as are available in the text, * returning -1 if the given number of digits was unavailable. */ - function scanMinimumNumberOfHexDigits(count) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true); + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } - function scanHexDigits(minCount, scanAsManyAsPossible) { + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { var digits = 0; var value = 0; + var allowSeparator = false; + var isPreviousTokenSeparator = false; while (digits < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { value = value * 16 + ch - 48 /* _0 */; } @@ -12046,10 +12236,14 @@ var ts; } pos++; digits++; + isPreviousTokenSeparator = false; } if (digits < minCount) { value = -1; } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return value; } function scanString(jsxAttributeString) { @@ -12200,7 +12394,7 @@ var ts; } } function scanHexadecimalEscape(numDigits) { - var escapedValue = scanExactNumberOfHexDigits(numDigits); + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); } @@ -12210,7 +12404,7 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1); + var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -12254,7 +12448,7 @@ var ts; if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { var start_1 = pos; pos += 2; - var value = scanExactNumberOfHexDigits(4); + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); pos = start_1; return value; } @@ -12306,8 +12500,27 @@ var ts; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. var numberOfDigits = 0; + var separatorAllowed = false; + var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); + // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; var valueOfCh = ch - 48 /* _0 */; if (!isDigit(ch) || valueOfCh >= base) { break; @@ -12315,11 +12528,17 @@ var ts; value = value * base + valueOfCh; pos++; numberOfDigits++; + isPreviousTokenSeparator = false; } // Invalid binaryIntegerLiteral or octalIntegerLiteral if (numberOfDigits === 0) { return -1; } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + return value; + } return value; } function scan() { @@ -12509,7 +12728,7 @@ var ts; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1); + var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); if (value < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -12855,7 +13074,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -12878,6 +13097,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: @@ -12888,55 +13108,30 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - pos++; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - pos++; return token = 39 /* AsteriskToken */; case 123 /* openBrace */: - pos++; return token = 17 /* OpenBraceToken */; case 125 /* closeBrace */: - pos++; return token = 18 /* CloseBraceToken */; case 91 /* openBracket */: - pos++; return token = 21 /* OpenBracketToken */; case 93 /* closeBracket */: - pos++; return token = 22 /* CloseBracketToken */; case 60 /* lessThan */: - pos++; return token = 27 /* LessThanToken */; - case 62 /* greaterThan */: - pos++; - return token = 29 /* GreaterThanToken */; case 61 /* equals */: - pos++; return token = 58 /* EqualsToken */; case 44 /* comma */: - pos++; return token = 26 /* CommaToken */; case 46 /* dot */: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24 /* DotDotDotToken */; - } return token = 23 /* DotToken */; - case 33 /* exclamation */: - pos++; - return token = 51 /* ExclamationToken */; - case 63 /* question */: - pos++; - return token = 55 /* QuestionToken */; } if (isIdentifierStart(ch, 6 /* Latest */)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } @@ -12944,7 +13139,7 @@ var ts; return token = 71 /* Identifier */; } else { - return pos += 1, token = 0 /* Unknown */; + return token = 0 /* Unknown */; } } function speculationHelper(callback, isLookahead) { @@ -13109,20 +13304,48 @@ var ts; case 267 /* SpreadAssignment */: return visitNode(cbNode, node.expression); case 147 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 150 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 149 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 265 /* PropertyAssignment */: - case 227 /* VariableDeclaration */: - case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 227 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); + case 177 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 161 /* FunctionType */: case 162 /* ConstructorType */: case 156 /* CallSignature */: @@ -13572,7 +13795,7 @@ var ts; // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost // all nodes would need extra state on them to store this info. // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 // grammar specification. // // An important thing about these context concepts. By default they are effectively inherited @@ -13750,15 +13973,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -14295,9 +14510,13 @@ var ts; return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); case 18 /* TypeParameters */: return isIdentifier(); - case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + if (token() === 26 /* CommaToken */) { + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 19 /* TypeArguments */: @@ -14317,7 +14536,7 @@ var ts; function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not + // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // // extends {} { @@ -14401,7 +14620,7 @@ var ts; } function isVariableDeclaratorListTerminator() { // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } @@ -14506,6 +14725,10 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -14904,7 +15127,7 @@ var ts; // We also do not need to check for negatives because any prefix operator would be part of a // parent unary expression. if (node.kind === 8 /* NumericLiteral */) { - node.numericLiteralFlags = scanner.getTokenFlags() & 496 /* NumericLiteralFlags */; + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; } nextToken(); finishNode(node); @@ -15014,7 +15237,7 @@ var ts; // // // - // We do *not* want to consume the > as we're consuming the expression for "". + // We do *not* want to consume the `>` as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } @@ -15754,7 +15977,7 @@ var ts; // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". // // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { @@ -15781,7 +16004,7 @@ var ts; // we're in '2' or '3'. Consume the assignment and return. // // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= + // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } @@ -15912,7 +16135,7 @@ var ts; var second = nextToken(); if (first === 19 /* OpenParenToken */) { if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". + // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. @@ -16113,7 +16336,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -16475,7 +16700,8 @@ var ts; // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" // For example: // var foo3 = require("subfolder - // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; expression = parseTokenNode(); } @@ -16523,7 +16749,7 @@ var ts; // treated as the invocation of "new Foo". We disambiguate that in code (to match // the original grammar) by making sure that if we see an ObjectCreationExpression // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think + // object creation only, and not at all as an invocation. Another way to think // about this is that for every "new" that we see, we will consume an argument list if // it is there as part of the *associated* object creation node. Any additional // argument lists we see, will become invocation expressions. @@ -16887,7 +17113,7 @@ var ts; } var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. + // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } // If we have a '<', then only parse this as a argument list if the type arguments @@ -17801,8 +18027,8 @@ var ts; // off. The grammar would look something like this: // // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. node.initializer = ts.hasModifier(node, 32 /* Static */) @@ -17884,6 +18110,7 @@ var ts; switch (token()) { case 19 /* OpenParenToken */: // Method declaration case 27 /* LessThanToken */: // Generic Method declaration + case 51 /* ExclamationToken */: // Non-null assertion on property name case 56 /* ColonToken */: // Type Annotation for declaration case 58 /* EqualsToken */: // Initializer for declaration case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on. @@ -18563,7 +18790,6 @@ var ts; scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. - var advanceToken = true; var state = 1 /* SawAsterisk */; var margin = undefined; // + 4 for leading '/** ' @@ -18575,17 +18801,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5 /* WhitespaceTrivia */) { + t = nextJSDocToken(); } - if (token() === 4 /* NewLineTrivia */) { + if (t === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + loop: while (true) { + switch (t) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); @@ -18594,7 +18820,6 @@ var ts; // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` state = 0 /* BeginningOfLine */; - advanceToken = false; margin = undefined; indent++; } @@ -18639,19 +18864,14 @@ var ts; indent += whitespace.length; break; case 1 /* EndOfFileToken */: - break; + break loop; default: // anything other than whitespace or asterisk at the beginning of the line starts the comment text state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -18736,7 +18956,8 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -18749,8 +18970,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { state = 0 /* BeginningOfLine */; @@ -18759,8 +18981,11 @@ var ts; indent = 0; break; case 57 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: // Done - break; + break loop; case 5 /* WhitespaceTrivia */: if (state === 2 /* SavingComments */) { pushComment(scanner.getTokenText()); @@ -18778,7 +19003,7 @@ var ts; if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; + indent += 1; break; } // record the * as a comment @@ -18788,15 +19013,11 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281 /* JSDocTag */, atToken.pos); @@ -18804,8 +19025,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -18876,10 +19096,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); @@ -18985,10 +19202,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -19033,8 +19247,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); @@ -19074,34 +19287,44 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0 /* Property */; + break; case "arg": case "argument": case "param": - return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1 /* Parameter */; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146 /* TypeParameter */); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -19120,6 +19343,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17 /* OpenBraceToken */); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -19298,7 +19529,7 @@ var ts; // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have + // depend if delta is positive or negative. If delta is positive then we have // something like: // // -------------------AAA----------------- @@ -19322,7 +19553,7 @@ var ts; element.pos = Math.min(element.pos, changeRangeNewEnd); // If the 'end' is after the change range, then we always adjust it by the delta // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we + // will depend on if delta is positive or negative. If delta is positive then we // have something like: // // -------------------AAA----------------- @@ -19786,12 +20017,14 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", + "esnext.promise": "lib.esnext.promise.d.ts", }), }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -20039,6 +20272,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -20329,19 +20569,19 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - var result = { + return { enable: typeAcquisition.enableAutoDiscovery, include: typeAcquisition.include || [], exclude: typeAcquisition.exclude || [] }; - return result; } return typeAcquisition; } @@ -21249,8 +21489,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - return options; + return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -21342,20 +21581,6 @@ var ts; * \/?$ # matches an optional trailing directory separator at the end of the string. */ var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - /** - * Tests for a path with multiple recursive directory wildcards. - * Matches **\** and **\a\**, but not **\a**b. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. - * (.*\/)? # optionally matches any number of characters followed by a directory separator. - * \*\* # matches a recursive directory wildcard "**" - * ($|\/) # matches either the end of the string or a directory separator. - */ - var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; /** * Tests for a path where .. appears after a recursive directory wildcard. * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* @@ -21524,9 +21749,6 @@ var ts; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } - else if (invalidMultipleRecursionPatterns.test(spec)) { - return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; - } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } @@ -21727,9 +21949,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -22283,8 +22505,8 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { @@ -22301,11 +22523,17 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - if (!compilerOptions.preserveSymlinks) { - resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + var originalPath = void 0; + if (!compilerOptions.preserveSymlinks && resolvedValue) { + originalPath = resolvedValue.path; + var path = realPath(resolved_1.value.path, host, traceEnabled); + if (path === originalPath) { + originalPath = undefined; + } + resolvedValue = __assign({}, resolvedValue, { path: path }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -22341,7 +22569,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -22355,6 +22585,49 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } /* @internal */ function directoryProbablyExists(directoryName, host) { // if host does not support 'directoryExists' assume that directory will exist @@ -22440,18 +22713,41 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { - var host = _a.host, traceEnabled = _a.traceEnabled; + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); + if (subModuleName === "") { + var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + } + else { + var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); + if (typeof jsPath === "string") { + subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -22609,13 +22905,18 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + /* @internal */ + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -22631,7 +22932,8 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { @@ -22676,7 +22978,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -22954,7 +23256,7 @@ var ts; // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -23377,7 +23679,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 /* StringLiteral */ || expr2.kind === 13 /* NoSubstitutionTemplateLiteral */); + } + function isNarrowableInOperands(left, right) { + return (left.kind === 9 /* StringLiteral */ || left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -23391,6 +23696,8 @@ var ts; isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 93 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); + case 92 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); case 26 /* CommaToken */: return isNarrowingExpression(expr.right); } @@ -24182,7 +24489,7 @@ var ts; // to the one we would get for: { <...>(...): T } // // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072 /* Signature */); @@ -24770,27 +25077,13 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' // is still pointing to 'module.exports'. // We do not want to consider this as 'export=' since a module can have only one of these. // Similarly we do not want to treat 'module.exports = exports' as an 'export='. var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { // Mark it as a module in case there are no other exports in the file setCommonJsModuleIndicator(node); return; @@ -24861,7 +25154,7 @@ var ts; if (node.kind === 195 /* BinaryExpression */) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { // This can be an alias for the 'exports' or 'module.exports' names, e.g. // var util = module.exports; // util.property = function ... @@ -24873,11 +25166,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -24993,7 +25282,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); @@ -25087,6 +25376,29 @@ var ts; return true; } } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } /** * Computes the transform flags for a node, given the transform flags of its subtree * @@ -25147,6 +25459,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); + case 181 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -25155,15 +25469,19 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; @@ -25174,19 +25492,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 180 /* PropertyAccessExpression */: - case 181 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25199,7 +25505,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25220,7 +25526,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25249,7 +25555,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; + return transformFlags & ~939525441 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25269,7 +25575,7 @@ var ts; transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -25295,7 +25601,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. @@ -25312,7 +25618,7 @@ var ts; transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25330,7 +25636,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25341,7 +25647,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -25353,7 +25659,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25367,7 +25673,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -25394,7 +25700,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25412,7 +25718,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -25423,7 +25729,7 @@ var ts; transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -25467,7 +25773,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25499,7 +25805,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -25524,19 +25830,31 @@ var ts; transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25550,7 +25868,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -25566,7 +25884,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25576,7 +25894,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25585,7 +25903,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25596,7 +25914,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -25605,7 +25923,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; + return transformFlags & ~977327425 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -25617,18 +25935,25 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; + var excludeFlags = 939525441 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: @@ -25637,8 +25962,6 @@ var ts; case 76 /* ConstKeyword */: case 233 /* EnumDeclaration */: case 268 /* EnumMember */: - case 185 /* TypeAssertionExpression */: - case 203 /* AsExpression */: case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. @@ -25755,7 +26078,8 @@ var ts; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. @@ -25766,11 +26090,11 @@ var ts; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; @@ -25783,7 +26107,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; case 179 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; + excludeFlags = 942740801 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. @@ -25802,7 +26126,7 @@ var ts; break; case 178 /* ArrayLiteralExpression */: case 183 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. @@ -25848,27 +26172,27 @@ var ts; case 182 /* CallExpression */: case 183 /* NewExpression */: case 178 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; case 234 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; + return 977327425 /* ModuleExcludes */; case 147 /* Parameter */: - return 536872257 /* ParameterExcludes */; + return 939525441 /* ParameterExcludes */; case 188 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; + return 1003902273 /* ArrowFunctionExcludes */; case 187 /* FunctionExpression */: case 229 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; + return 1003935041 /* FunctionExcludes */; case 228 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; + return 948962625 /* VariableDeclarationListExcludes */; case 230 /* ClassDeclaration */: case 200 /* ClassExpression */: - return 539358529 /* ClassExcludes */; + return 942011713 /* ClassExcludes */; case 153 /* Constructor */: - return 601015617 /* ConstructorExcludes */; + return 1003668801 /* ConstructorExcludes */; case 152 /* MethodDeclaration */: case 154 /* GetAccessor */: case 155 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; + return 1003668801 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: case 130 /* NeverKeyword */: @@ -25887,14 +26211,23 @@ var ts; case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 179 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; + return 942740801 /* ObjectLiteralExcludes */; case 264 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; + return 940574017 /* CatchClauseExcludes */; case 175 /* ObjectBindingPattern */: case 176 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; + return 940049729 /* BindingPatternExcludes */; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + case 186 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; default: - return 536872257 /* NodeExcludes */; + return 939525441 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -25910,7 +26243,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -26006,8 +26339,9 @@ var ts; visitType(type.modifiersType); } function visitSignature(signature) { - if (signature.typePredicate) { - visitType(signature.typePredicate.type); + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); } ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { @@ -26195,6 +26529,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -26228,16 +26567,32 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); + }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { node = ts.getParseTreeNode(node, ts.isExpression); return node ? getContextualType(node) : undefined; }, + isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { node = ts.getParseTreeNode(node, ts.isCallLikeExpression); @@ -26252,7 +26607,11 @@ var ts; }, isValidPropertyAccess: function (node, propertyName) { node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (node, type, property) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); }, getSignatureFromDeclaration: function (declaration) { declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); @@ -26276,7 +26635,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -26318,11 +26677,17 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -26368,13 +26733,15 @@ var ts; var markerSubType = createType(32768 /* TypeParameter */); markerSubType.constraint = markerSuperType; var markerOtherType = createType(32768 /* TypeParameter */); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var reverseMappedCache = ts.createMap(); var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -26541,20 +26908,20 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - var _displayBuilder; var TypeSystemPropertyName; (function (TypeSystemPropertyName) { TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { CheckMode[CheckMode["Normal"] = 0] = "Normal"; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; })(CheckMode || (CheckMode = {})); var CallbackCheck; (function (CallbackCheck) { @@ -26584,6 +26951,142 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + /** + * @deprecated + */ + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -26599,10 +27102,12 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -26861,7 +27366,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage @@ -26949,10 +27454,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -27012,7 +27518,7 @@ var ts; if (location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. - if (result = moduleExports.get("default")) { + if (result = moduleExports.get("default" /* Default */)) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { break loop; @@ -27168,14 +27674,14 @@ var ts; } break; } - if (location.kind !== 208 /* Block */) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. - // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // If `result === lastNonBlockLocation.symbol`, that means that we are somewhere inside `lastNonBlockLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; @@ -27187,7 +27693,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -27250,6 +27758,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -27418,6 +27940,41 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a default member specified + if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -27426,15 +27983,15 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -27514,7 +28071,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } var symbol = symbolFromModule && symbolFromVariable ? @@ -27766,7 +28323,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -27801,8 +28358,42 @@ var ts; // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -27855,7 +28446,7 @@ var ts; if (!source) return; source.forEach(function (sourceSymbol, id) { - if (id === "default") + if (id === "default" /* Default */) return; var targetSymbol = target.get(id); if (!targetSymbol) { @@ -28040,11 +28631,14 @@ var ts; } var visitedSymbolTables = []; return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols) { + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols); + var result = trySymbolTable(symbols, ignoreQualification); visitedSymbolTables.pop(); return result; } @@ -28054,20 +28648,20 @@ var ts; // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function isUMDExportSymbol(symbol) { return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } - function trySymbolTable(symbols) { + function trySymbolTable(symbols, ignoreQualification) { // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.escapedName))) { + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; } // Check if symbol is any of the alias @@ -28078,12 +28672,13 @@ var ts; // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; } // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -28138,6 +28733,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -28265,97 +28864,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 3112960 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 162 /* ConstructorType */ : 161 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 157 /* ConstructSignature */ : 156 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8 /* NoTruncation */) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256 /* UseFullyQualifiedType */) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096 /* SuppressAnyReturnType */) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1 /* WriteArrayAsGenericType */) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64 /* WriteTypeArgumentsOfSignature */) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; return undefined; @@ -28392,6 +29025,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); } if (type.flags & 2048 /* Void */) { @@ -28413,10 +29051,13 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -28430,7 +29071,7 @@ var ts; // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -28443,7 +29084,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } return undefined; @@ -28469,7 +29110,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); @@ -28478,7 +29119,7 @@ var ts; var symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); @@ -28501,10 +29142,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + if (isConstructorObject) { + return createTypeNodeFromObjectType(type); + } + else { + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } } } else { @@ -28521,7 +29168,8 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -28546,11 +29194,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304 /* InObjectTypeLiteral */; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); @@ -28564,7 +29212,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -28578,12 +29226,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -28662,7 +29315,10 @@ var ts; typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); + var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? + createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : + resolvedType.stringIndexInfo; + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -28673,9 +29329,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + } + } var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -28722,20 +29393,30 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); } var returnTypeNode; - if (signature.typePredicate) { - var typePredicate = signature.typePredicate; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : ts.createThisTypeNode(); @@ -28746,7 +29427,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256 /* SuppressAnyReturnType */) { if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { returnTypeNode = undefined; } @@ -28754,14 +29435,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -28772,7 +29456,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -28798,47 +29482,22 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -28866,11 +29525,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -28933,6 +29674,9 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -28942,7 +29686,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } switch (declaration.kind) { @@ -28961,727 +29705,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); - } - } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || - // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 33585807 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - // In a literal enum type with a single member E { A }, E and E.A denote the - // same type. We always display this type simply as E. - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - } - else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024 /* UniqueESSymbol */) { - if (flags & 131072 /* AllowUniqueESSymbolType */) { - writeKeyword(writer, 140 /* UniqueKeyword */); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137 /* SymbolKeyword */); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288 /* Index */) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128 /* InElementType */); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - else if (type.flags & 1048576 /* IndexedAccess */) { - writeType(type.objectType, 128 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { - writeAnonymousType(type, flags); - } - else { - // Write the type reference in the format f.g.C where A and B are type arguments - // for outer type parameters, and f and g are the respective declaring containers of those - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - // When type parameters are their own type arguments for the whole group (i.e. we have - // the default outer type arguments), we don't show the group. - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 131072 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - // If type is an anonymous type literal in a type alias declaration, use type alias name - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - else { - // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead - // of types allows us to catch circular references to instantiations of the same anonymous type - // However, in case of class expressions, we want to write both the static side and the instance side. - // We skip adding the static side so that the instance side has a chance to be written - // before checking for circular references. - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || // is exported function symbol - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it - ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128 /* InElementType */) { - return true; - } - else if (flags & 512 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { - if (p.flags & 4194304 /* Prototype */) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 512 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 16 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -29819,8 +29842,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -29854,6 +29877,10 @@ var ts; if (propertyName === 3 /* ResolvedReturnType */) { return target.resolvedReturnType; } + if (propertyName === 4 /* ResolvedBaseConstraint */) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will @@ -29978,7 +30005,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -29999,7 +30027,7 @@ var ts; } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -30020,7 +30048,7 @@ var ts; type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -30046,11 +30074,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === 216 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 216 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 217 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 217 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -30061,11 +30089,11 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } + var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; // Use type from type annotation if one is present - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, /*optional*/ !!declaration.questionToken && includeOptionality); + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && declaration.kind === 227 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && @@ -30107,23 +30135,19 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for return trueType; } - // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 266 /* ShorthandPropertyAssignment */) { - return checkIdentifier(declaration.name); - } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); @@ -30170,7 +30194,7 @@ var ts; types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } } - var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + var type = jsDocType || getUnionType(types, 2 /* Subtype */); return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if @@ -30264,19 +30288,13 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 1024 /* UniqueESSymbol */ && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 1024 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } - // During a normal type check we'll never get to here with a property assignment (the check of the containing - // object literal uses a different path). We exclude widening only so that language services and type verification - // tools see the actual type. - if (declaration.kind === 265 /* PropertyAssignment */) { - return type; - } return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any - type = declaration.dotDotDotToken ? anyArrayType : anyType; + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && noImplicitAny) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { @@ -30290,6 +30308,12 @@ var ts; var memberDeclaration = root.kind === 147 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { @@ -30323,9 +30347,39 @@ var ts; declaration.kind === 180 /* PropertyAccessExpression */ && declaration.parent.kind === 195 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else { + else if (ts.isJSDocPropertyTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } + else { + ts.Debug.fail("Unhandled declaration kind! " + ts.SyntaxKind[declaration.kind]); + } if (!popTypeResolution()) { type = reportCircularityError(symbol); } @@ -30492,6 +30546,9 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { return getTypeOfVariableOrParameterOrProperty(symbol); } @@ -30705,10 +30762,10 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = ts.emptyArray; + type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); @@ -30731,22 +30788,29 @@ var ts; var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; + return type.resolvedBaseTypes = ts.emptyArray; } baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === unknownType) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); - return; + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; } - type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -30784,7 +30848,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); } } else { @@ -30949,7 +31013,7 @@ var ts; } } if (memberTypeList.length) { - var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); if (enumType_1.flags & 131072 /* Union */) { enumType_1.flags |= 256 /* EnumLiteral */; enumType_1.symbol = symbol; @@ -31047,7 +31111,7 @@ var ts; */ function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isThislessType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); } /** * A function-like declaration is considered free of `this` references if it has a return type @@ -31309,18 +31373,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -31350,6 +31415,7 @@ var ts; if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); var thisArgument = ts.lastOrUndefined(typeArguments); for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { var baseType = baseTypes_1[_i]; @@ -31377,27 +31443,28 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; + sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -31408,7 +31475,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -31467,13 +31534,13 @@ var ts; var s = signature; // Union the result types when more than one signature matches if (unionSignatures.length > 1) { - s = cloneSignature(signature); + var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); } - // Clear resolved return type we possibly got from cloneSignature - s.resolvedReturnType = undefined; + s = cloneSignature(signature); + s.thisParameter = thisParameter; s.unionSignatures = unionSignatures; } (result || (result = [])).push(s); @@ -31495,7 +31562,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union @@ -31591,6 +31658,7 @@ var ts; if (symbol.exports) { members = getExportsOfSymbol(symbol); } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -31622,6 +31690,23 @@ var ts; } } } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var readonlyMask = type.mappedType.declaration.readonlyToken ? false : true; + var optionalMask = type.mappedType.declaration.questionToken ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -31752,6 +31837,9 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } else if (type.objectFlags & 16 /* Anonymous */) { resolveAnonymousTypeMembers(type); } @@ -31843,12 +31931,17 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { + // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. + // to avoid this, return `undefined`. + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -31872,29 +31965,30 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; @@ -31914,7 +32008,7 @@ var ts; return stringType; } if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -31930,7 +32024,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -31992,15 +32086,14 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; - var types = containingType.types; var isUnion = containingType.flags & 131072 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var current = types_5[_i]; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -32031,8 +32124,8 @@ var ts; var propTypes = []; var declarations = []; var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -32145,7 +32238,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); + return getUnionType(propTypes, 2 /* Subtype */); } } return undefined; @@ -32203,7 +32296,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -32211,27 +32304,27 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 71 /* Identifier */) { - return { - kind: 1 /* Identifier */, - parameterName: parameterName ? parameterName.escapedText : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; + return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 + parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); } else { - return { - kind: 0 /* This */, - type: getTypeFromTypeNode(node.type) - }; + return createThisTypePredicate(type); } } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } /** * Gets the minimum number of type arguments needed to satisfy all non-optional type * parameters. @@ -32338,11 +32431,8 @@ var ts; : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -32352,7 +32442,7 @@ var ts; // b) It references `arguments` somewhere var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -32467,6 +32557,28 @@ var ts; return getTypeOfSymbol(signature.thisParameter); } } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var declaration = signature.declaration; + signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? + createTypePredicateFromTypePredicateNode(declaration.type) : + noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -32477,7 +32589,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } else { type = getReturnTypeFromBody(signature.declaration); @@ -32624,12 +32736,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -32650,8 +32762,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -32701,7 +32813,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) @@ -33142,14 +33254,14 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -33214,7 +33326,8 @@ var ts; // expression constructs such as array literals and the || and ?: operators). Named types can // circularly reference themselves and therefore cannot be subtype reduced during their declaration. // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } if (types.length === 0) { return neverType; } @@ -33226,11 +33339,15 @@ var ts; if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsLiteralOrUniqueESSymbol) { - removeRedundantLiteralTypes(typeSet); + switch (unionReduction) { + case 1 /* Literal */: + if (typeSet.containsLiteralOrUniqueESSymbol) { + removeRedundantLiteralTypes(typeSet); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : @@ -33239,6 +33356,40 @@ var ts; } return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } // This function assumes the constituent type list is sorted and deduplicated. function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { @@ -33268,7 +33419,7 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } @@ -33301,8 +33452,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } @@ -33339,8 +33490,7 @@ var ts; // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), - /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); @@ -33369,7 +33519,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -33418,6 +33568,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -33491,42 +33642,64 @@ var ts; } return false; } + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // undefined if no transformation is possible. - function getTransformedIndexedAccessType(type) { + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); + if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a + // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen + // eventually anyway, but it easier to reason about. + if (ts.some(objectType.types, isMappedTypeToNever)) { + var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); + return getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { // If the index type is generic, or if the object type is generic and doesn't originate in an expression, // we are performing a higher-order index access where we cannot meaningfully access the properties of the @@ -33632,10 +33805,7 @@ var ts; if (right.flags & 131072 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 33554432 /* NonPrimitive */) { - return nonPrimitiveType; - } - if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */)) { + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */ | 33554432 /* NonPrimitive */)) { return left; } var members = ts.createSymbolTable(); @@ -33688,8 +33858,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= propagatedFlags; - spread.flags |= 2097152 /* FreshLiteral */ | 8388608 /* ContainsObjectLiteral */; + spread.flags |= propagatedFlags | 8388608 /* ContainsObjectLiteral */; spread.objectFlags |= (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } @@ -33909,7 +34078,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -33931,7 +34100,7 @@ var ts; result.target = typeParameter; return result; } - function cloneTypePredicate(predicate, mapper) { + function instantiateTypePredicate(predicate, mapper) { if (ts.isIdentifierTypePredicate(predicate)) { return { kind: 1 /* Identifier */, @@ -33949,7 +34118,6 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { // First create a fresh set of type parameters, then include a mapping from the old to the // new type parameters in the mapper function. Finally store this mapper in the new type @@ -33961,11 +34129,12 @@ var ts; tp.mapper = mapper; } } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), - /*resolvedReturnType*/ undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -34113,7 +34282,7 @@ var ts; } } if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { - return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return getUnionType(instantiateTypes(type.types, mapper), 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (type.flags & 262144 /* Intersection */) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); @@ -34318,7 +34487,7 @@ var ts; // with respect to T. var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -34338,11 +34507,13 @@ var ts; } var sourceReturnType = getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); } @@ -34457,7 +34628,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -34542,6 +34713,9 @@ var ts; } return false; } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return source.flags & 67108864 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -34569,10 +34743,24 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -34582,8 +34770,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } if (!message) { if (relation === comparableRelation) { @@ -35064,7 +35252,7 @@ var ts; } else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. + // A is the constraint of T. var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -35099,7 +35287,7 @@ var ts; } else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. + // A is the constraint of S. var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -35107,10 +35295,11 @@ var ts; return result; } } - else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. + else if (target.flags & 1048576 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -35244,6 +35433,9 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { @@ -35454,6 +35646,9 @@ var ts; var result = -1 /* True */; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -35623,7 +35818,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -35814,17 +36009,25 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } return result; } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -35850,7 +36053,7 @@ var ts; var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); return primaryTypes.length ? getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : - getUnionType(types, /*subtypeReduction*/ true); + getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -35916,8 +36119,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -36108,7 +36311,7 @@ var ts; // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). - return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -36195,6 +36398,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173 /* MappedType */: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -36250,6 +36456,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -36260,6 +36467,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -36286,7 +36494,7 @@ var ts; function isTypeParameterAtTopLevel(type, typeParameter) { return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - /** Create an object with properties named in the string literal type. Every property has type `{}` */ + /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { @@ -36295,7 +36503,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4 /* Property */, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -36311,42 +36519,45 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { + function inferTypeForHomomorphicMappedType(source, target) { + var key = source.id + "," + target.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target) { var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0 /* String */); - if (properties.length === 0 && !indexInfo) { + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var inference = createInferenceInfo(typeParameter); - var inferences = [inference]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 16777216 /* Optional */; - var members = ts.createSymbolTable(); + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var propType = getTypeOfSymbol(prop); - // If any property contains context sensitive functions that have been skipped, the source type - // is incomplete and we can't infer a meaningful input type. - if (propType.flags & 16777216 /* ContainsAnyFunctionType */) { + if (getTypeOfSymbol(prop).flags & 16777216 /* ContainsAnyFunctionType */) { return undefined; } - var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; - var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); - inferredProp.declarations = prop.declarations; - inferredProp.type = inferTargetType(propType); - members.set(prop.escapedName, inferredProp); - } - if (indexInfo) { - indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); - return inference.candidates ? getUnionType(inference.candidates, /*subtypeReduction*/ true) : emptyObjectType; } + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + } + function inferReverseMappedType(sourceType, target) { + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -36361,10 +36572,11 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { + function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -36433,25 +36645,27 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - // We give lowest priority to inferences of implicitNeverType (which is used as the - // element type for empty array literals). Thus, inferences from empty array literals - // only matter when no other inferences are made. - var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; @@ -36467,15 +36681,15 @@ var ts; } } else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -36501,7 +36715,7 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2 /* NakedTypeVariable */; + priority |= 1 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -36545,9 +36759,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -36580,16 +36794,10 @@ var ts; // such that direct inferences to T get priority over inferences to Partial, for example. var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); - if (ts.contains(mappedTypeStack, key)) { - return; - } - (mappedTypeStack || (mappedTypeStack = [])).push(key); - var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); - mappedTypeStack.pop(); + var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4 /* MappedType */; + priority |= 2 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -36635,8 +36843,10 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromContravariantTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); @@ -36663,8 +36873,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -36696,7 +36906,7 @@ var ts; if (candidates.length > 1) { var objectLiterals = ts.filter(candidates, isObjectLiteralType); if (objectLiterals.length) { - var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true)); + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); } } @@ -36721,10 +36931,19 @@ var ts; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : - context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -36773,7 +36992,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -36968,8 +37188,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -37035,16 +37255,6 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576 /* 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) { @@ -37081,7 +37291,7 @@ var ts; parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -37120,7 +37330,7 @@ var ts; var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -37239,15 +37449,15 @@ var ts; // Apply a mapping function to a type and return the resulting type. If the source type // is a union type, the mapping function is applied to each constituent type and a union // of the resulting types is returned. - function mapType(type, mapper) { + function mapType(type, mapper, noReductions) { if (!(type.flags & 131072 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -37261,7 +37471,7 @@ var ts; } } } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -37312,7 +37522,7 @@ var ts; return elementType.flags & 16384 /* Never */ ? autoArrayType : createArrayType(elementType.flags & 131072 /* Union */ ? - getUnionType(elementType.types, /*subtypeReduction*/ true) : + getUnionType(elementType.types, 2 /* Subtype */) : elementType); } // We perform subtype reduction upon obtaining the final array type from an evolving array type. @@ -37327,8 +37537,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 16384 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -37374,10 +37584,7 @@ var ts; var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } + return apparentType !== unknownType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); } } return false; @@ -37627,7 +37834,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at @@ -37655,7 +37862,7 @@ var ts; // path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -37675,7 +37882,7 @@ var ts; firstAntecedentType = flowType; } var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis + // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. var cached_1 = cache.get(key); @@ -37698,7 +37905,7 @@ var ts; } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } @@ -37729,6 +37936,23 @@ var ts; } return type; } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (131072 /* Union */ | 65536 /* Object */)) || (type.flags & 32768 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { case 58 /* EqualsToken */: @@ -37740,10 +37964,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && (right_1.kind === 9 /* StringLiteral */ || right_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && (left_1.kind === 9 /* StringLiteral */ || left_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -37764,6 +37988,12 @@ var ts; break; case 93 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); + case 92 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if ((expr.left.kind === 9 /* StringLiteral */ || expr.left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; case 26 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } @@ -37848,7 +38078,7 @@ var ts; var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -37928,7 +38158,7 @@ var ts; return type; } var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; + var predicate = getTypePredicateOfSignature(signature); if (!predicate) { return type; } @@ -38062,22 +38292,28 @@ var ts; var parent = node.parent; return parent.kind === 180 /* PropertyAccessExpression */ || parent.kind === 182 /* CallExpression */ && parent.expression === node || - parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 204 /* NonNullExpression */ || + parent.kind === 177 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getDeclaredOrApparentType(symbol, node) { + function getApparentTypeForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - var type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } return type; } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -38103,9 +38339,9 @@ var ts; return getTypeOfSymbol(symbol); } // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. - if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; @@ -38146,7 +38382,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -38182,6 +38418,7 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -38193,7 +38430,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || node.parent.kind === 204 /* NonNullExpression */ || @@ -38395,6 +38632,15 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. @@ -38429,11 +38675,6 @@ var ts; return type; } } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -38708,7 +38949,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -38729,7 +38970,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. indexOfParameter -= 1; @@ -38757,7 +38998,7 @@ var ts; // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer || node.kind === 58 /* EqualsToken */) { + if (ts.hasInitializer(declaration) && node === declaration.initializer) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -38846,7 +39087,7 @@ var ts; // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. @@ -38875,12 +39116,6 @@ var ts; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - // For completions after `x === ` - return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; default: return undefined; } @@ -38909,10 +39144,10 @@ var ts; return mapType(type, function (t) { var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; - }); + }, /*noReductions*/ true); } function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { @@ -39081,12 +39316,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 198 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 183 /* NewExpression */: - if (node.kind === 94 /* NewKeyword */) { - return getContextualType(parent); - } - // falls through case 182 /* CallExpression */: + case 183 /* NewExpression */: return getContextualTypeForArgument(parent, node); case 185 /* TypeAssertionExpression */: case 203 /* AsExpression */: @@ -39121,12 +39352,6 @@ var ts; case 252 /* JsxOpeningElement */: case 251 /* JsxSelfClosingElement */: return getAttributesTypeFromJsxOpeningLikeElement(parent); - case 261 /* CaseClause */: { - if (node.kind === 73 /* CaseKeyword */) { - var switchStatement = parent.parent.parent; - return getTypeOfExpression(switchStatement.expression); - } - } } return undefined; } @@ -39137,7 +39362,7 @@ var ts; // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + var signatures = getSignaturesOfType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -39190,8 +39415,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -39212,8 +39437,6 @@ var ts; var result; if (signatureList) { result = cloneSignature(signatureList[0]); - // Clear resolved return type we possibly got from cloneSignature - result.resolvedReturnType = undefined; result.unionSignatures = signatureList; } return result; @@ -39287,7 +39510,7 @@ var ts; if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -39297,7 +39520,7 @@ var ts; } } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : + getUnionType(elementTypes, 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { @@ -39369,7 +39592,7 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, checkMode) { @@ -39379,7 +39602,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 0; + var propagatedFlags = 2097152 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 175 /* ObjectBindingPattern */ || contextualType.pattern.kind === 179 /* ObjectLiteralExpression */); @@ -39548,13 +39771,13 @@ var ts; type.flags & 65536 /* Object */ && !isGenericMappedType(type) || type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node); + function checkJsxSelfClosingElement(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); return getJsxGlobalElementType() || anyType; } - function checkJsxElement(node) { + function checkJsxElement(node, checkMode) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -39564,8 +39787,8 @@ var ts; } return getJsxGlobalElementType() || anyType; } - function checkJsxFragment(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + function checkJsxFragment(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); } @@ -39593,6 +39816,11 @@ var ts; ts.Debug.fail(); } } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } /** * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. * @@ -39602,11 +39830,10 @@ var ts; * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, * which also calls getSpreadType. */ - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); var spread = emptyObjectType; - var attributesArray = []; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; @@ -39615,9 +39842,7 @@ var ts; var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; // is sugar for + var exprType = checkJsxAttribute(attributeDecl, checkMode); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -39627,24 +39852,22 @@ var ts; attributeSymbol.type = exprType; attributeSymbol.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); - attributesArray.push(attributeSymbol); if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } } else { ts.Debug.assert(attributeDecl.kind === 259 /* JsxSpreadAttribute */); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - attributesArray = []; + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpression(attributeDecl.expression); + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 67108864 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -39652,18 +39875,8 @@ var ts; } } if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createSymbolTable(); - for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { - var attr = attributesArray_1[_b]; - if (!filter || filter(attr)) { - attributesTable.set(attr.escapedName, attr); - } + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864 /* JsxAttributes */); } } // Handle children attribute @@ -39678,27 +39891,27 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + createArrayType(getUnionType(childrenTypes)); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, 67108864 /* JsxAttributes */); } } if (hasSpreadAnyType) { return anyType; } - var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); - return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : - typeToIntersect ? typeToIntersect : attributeType; + return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ - function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + function createJsxAttributesType() { + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); result.flags |= 67108864 /* JsxAttributes */ | 8388608 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; @@ -39727,7 +39940,7 @@ var ts; * @param node a JSXAttributes to be resolved of its type */ function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } function getJsxType(name) { var jsxType = jsxTypes.get(name); @@ -39779,7 +39992,7 @@ var ts; * element is not a class element, or the class element type cannot be determined, returns 'undefined'. * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ - function getJsxElementInstanceType(node, valueType) { + function getJsxElementInstanceType(node, valueType, sourceAttributesType) { ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' @@ -39796,19 +40009,27 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0, isJavascript); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + } + else { + // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -39976,19 +40197,19 @@ var ts; * * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature + * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) * @return attributes type if able to resolve the type of node * anyType if there is no type ElementAttributesProperty or there is an error * emptyObjectType if there is no "prop" in the element instance type */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), /*subtypeReduction*/ true); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + }), 2 /* Subtype */); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type if (elementType.flags & 2 /* String */) { @@ -40016,7 +40237,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -40026,7 +40247,7 @@ var ts; return statelessAttributesType; } // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { + if (elementClassType && sourceAttributesType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } if (isTypeAny(elemInstanceType)) { @@ -40102,14 +40323,20 @@ var ts; * @param node a custom JSX opening-like element * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { + if (!sourceAttributesType) { + // This ensures we cache non-inference uses of this calculation (ie, contextual types or services) + var links = getNodeLinks(node); + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { + var elemClassType = getJsxGlobalElementClassType(); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); + } + return links[linkLocation]; + } + else { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } - return links[linkLocation]; } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -40123,7 +40350,7 @@ var ts; else { // Because in language service, the given JSX opening-like element may be incomplete and therefore, // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ true); } } /** @@ -40136,7 +40363,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ false); } } /** @@ -40188,7 +40415,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node) { + function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -40210,7 +40437,7 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node); + checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); } else { checkJsxChildren(node.parent); @@ -40256,22 +40483,20 @@ var ts; * Check assignablity between given attributes property, "source attributes", and the "target attributes" * @param openingLikeElement an opening-like JSX element to check its JSXAttributes */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { // The function involves following steps: // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); - }); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); + // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, /*shouldIncludeAllStatelessAttributesType*/ false); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { @@ -40281,12 +40506,17 @@ var ts; // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; - if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); + if (!ts.isJsxAttribute(attribute)) { + continue; + } + var attrName = attribute.name; + var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); // We break here so that errors won't be cascading break; } @@ -40416,16 +40646,16 @@ var ts; return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } @@ -40439,15 +40669,20 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var propType; - var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; var apparentType = getApparentType(getWidenedType(leftType)); if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } return apparentType; } var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { @@ -40464,12 +40699,6 @@ var ts; else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); - // Reset the referenced-ness of the LHS expression if this access refers to a const enum or const enum only module - leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && - !(isNonLocalAlias(leftSymbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { - getSymbolLinks(leftSymbol).referenced = undefined; - } getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); if (assignmentKind) { @@ -40478,7 +40707,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -40545,6 +40774,9 @@ var ts; * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. */ function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } var classType = getTypeOfSymbol(prop.parent); while (true) { classType = getSuperClass(classType); @@ -40591,7 +40823,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -40696,32 +40928,43 @@ var ts; return res > max ? undefined : res; } 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; - } - else { - prop.isReferenced = true; + if (!prop || !noUnusedIdentifiers || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + 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; + } + else { + prop.isReferenced = true; + } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 180 /* PropertyAccessExpression */ - ? node.expression - : node.left; + var left = node.kind === 180 /* PropertyAccessExpression */ ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, type) { + var propType = getTypeOfFuncClassEnumModule(method); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var thisType = getThisTypeOfSignature(sig); + return !thisType || isTypeAssignableTo(type, thisType); + }); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(type, propertyName); @@ -41026,10 +41269,15 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } + function inferJsxTypeArguments(signature, sourceAttributesType, context) { + var paramType = getTypeAtPosition(signature, 0); + inferTypes(context.inferences, sourceAttributesType, paramType); + return getInferredTypes(context); + } function inferTypeArguments(node, signature, args, excludeArgument, context) { // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { @@ -41066,7 +41314,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -41122,7 +41370,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -41731,7 +41979,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { excludeArgument = undefined; @@ -41770,7 +42018,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -41804,7 +42052,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); } return resolveErrorCall(node); } @@ -41885,7 +42133,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -41925,6 +42173,26 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 /* Call */ + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -41938,7 +42206,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -41986,6 +42254,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -42030,8 +42299,8 @@ var ts; if (elementType.flags & 131072 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -42215,16 +42484,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default" /* Default */)) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); newSymbol.target = resolveSymbol(symbol); @@ -42232,7 +42503,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -42314,7 +42585,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks) { var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { + if (declaration && ts.hasInitializer(declaration)) { return getOptionalType(type); } } @@ -42423,7 +42694,6 @@ var ts; return promiseType; } function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } @@ -42440,9 +42710,9 @@ var ts; } } else { - var types = void 0; + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (functionFlags & 1 /* Generator */) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 /* Async */ ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function @@ -42454,7 +42724,6 @@ var ts; } } else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) { // For an async function, the return type will not be never, but rather a Promise for never. return functionFlags & 2 /* Async */ @@ -42469,8 +42738,9 @@ var ts; } } // Return a union of the return expression types. - type = getUnionType(types, /*subtypeReduction*/ true); + type = getUnionType(types, 2 /* Subtype */); } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!contextualSignature) { reportErrorsFromWidening(func, type); } @@ -42552,6 +42822,7 @@ var ts; } return true; } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -42577,8 +42848,7 @@ var ts; hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */)) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -42586,6 +42856,17 @@ var ts; } return aggregatedTypes; } + function mayReturnNever(func) { + switch (func.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + return true; + case 152 /* MethodDeclaration */: + return func.parent.kind === 179 /* ObjectLiteralExpression */; + default: + return false; + } + } /** * TypeScript Specification 1.0 (6.3) - July 2014 * An explicitly typed function whose return type isn't the Void type, @@ -42887,8 +43168,8 @@ var ts; } if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -42963,6 +43244,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -43303,7 +43587,7 @@ var ts; leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: checkAssignmentOperator(rightType); @@ -43439,7 +43723,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getUnionType([type1, type2], /*subtypeReduction*/ true); + return getUnionType([type1, type2], 2 /* Subtype */); } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -43458,7 +43742,7 @@ var ts; node.contextualType = contextualType; node.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : - contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; var result = checkExpression(node, checkMode); node.contextualType = saveContextualType; node.contextualMapper = saveContextualMapper; @@ -43467,6 +43751,9 @@ var ts; function checkExpressionCached(node, checkMode) { var links = getNodeLinks(node); if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } // When computing a type that we're going to cache, we need to ignore any ongoing control flow // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart // to the top of the stack ensures all transient types are computed from a known point. @@ -43489,12 +43776,12 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 131072 /* Union */ && !(contextualType.flags & 8 /* Boolean */)) { + if (contextualType.flags & 393216 /* UnionOrIntersection */ && !(contextualType.flags & 8 /* Boolean */)) { // If the contextual type is a union containing both of the 'true' and 'false' types we // don't consider it a literal context for boolean literals. - var types_19 = contextualType.types; - return ts.some(types_19, function (t) { - return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_19, trueType) && containsType(types_19, falseType)) && + var types_18 = contextualType.types; + return ts.some(types_18, function (t) { + return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_18, trueType) && containsType(types_18, falseType)) && isLiteralOfContextualType(candidateType, t); }); } @@ -43620,9 +43907,10 @@ var ts; // - target in rhs of import statement var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -43714,11 +44002,11 @@ var ts; case 260 /* JsxExpression */: return checkJsxExpression(node, checkMode); case 250 /* JsxElement */: - return checkJsxElement(node); + return checkJsxElement(node, checkMode); case 251 /* JsxSelfClosingElement */: - return checkJsxSelfClosingElement(node); + return checkJsxSelfClosingElement(node, checkMode); case 254 /* JsxFragment */: - return checkJsxFragment(node); + return checkJsxFragment(node, checkMode); case 258 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); case 252 /* JsxOpeningElement */: @@ -43767,7 +44055,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { @@ -43798,7 +44086,7 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); if (!typePredicate) { return; } @@ -43813,7 +44101,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } @@ -44144,22 +44432,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && @@ -44375,6 +44647,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -44742,7 +45017,7 @@ var ts; } return undefined; } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); } /** * Gets the "awaited type" of a type. @@ -44775,7 +45050,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -44975,7 +45250,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -45332,22 +45607,35 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 152 /* MethodDeclaration */ || member.kind === 150 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; } - } - else if (member.kind === 153 /* Constructor */) { + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } - } + break; + case 158 /* IndexSignature */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } @@ -45664,7 +45952,9 @@ var ts; // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); - checkSourceElement(node.type); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } // JSDoc `function(string, string): string` syntax results in parameters with no name if (!node.name) { return; @@ -45713,13 +46003,19 @@ var ts; if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + } checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -45914,7 +46210,7 @@ var ts; // Grammar checking checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 + // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, @@ -46003,7 +46299,7 @@ var ts; var arrayTypes = inputType.types; var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } else if (arrayType.flags & 524322 /* StringLike */) { @@ -46048,7 +46344,7 @@ var ts; if (arrayElementType.flags & 524322 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); } return arrayElementType; } @@ -46135,7 +46431,7 @@ var ts; } return undefined; } - var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); if (checkAssignability && errorNode && iteratedType) { // If `checkAssignability` was specified, we were called from @@ -46203,7 +46499,7 @@ var ts; } return undefined; } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); if (isTypeAny(nextResult)) { return undefined; } @@ -46258,56 +46554,56 @@ var ts; } function checkReturnStatement(node) { // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } + if (checkGrammarStatementInAmbientContext(node)) { + return; } var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // A generator does not need its return expressions checked against its return type. // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added + // TODO: Check return types of generators when return type tracking is added // for generators. return; } - if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 155 /* SetAccessor */) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } + else if (func.kind === 155 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 153 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } + } + else if (func.kind === 153 /* Constructor */) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - // If the function has a return type, but promisedType is - // undefined, an error will be reported in checkAsyncFunctionReturnType - // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2 /* Async */) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); } } + else { + checkTypeAssignableTo(exprType, returnType, node); + } } - else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - // The function has a return type, but the return statement doesn't have an expression. - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } + } + else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkWithStatement(node) { @@ -46469,7 +46765,8 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -46588,9 +46885,11 @@ var ts; // type parameter at this position, we report an error. var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } } // If the type parameter node has a default and it is not identical to the default // for the type parameter at this position, we report an error. @@ -46663,7 +46962,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -46693,7 +46995,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -46708,6 +47016,35 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_6 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_6(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { @@ -47011,6 +47348,7 @@ var ts; case 37 /* PlusToken */: return left + right; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; + case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } break; @@ -48235,6 +48573,7 @@ var ts; } return undefined; case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript @@ -48360,7 +48699,7 @@ var ts; // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -48407,35 +48746,28 @@ var ts; return ts.typeHasCallOrConstructSignatures(type, checker); } function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_4 = []; - var name_4 = symbol.escapedName; - ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_4); - if (symbol) { - symbols_4.push(symbol); - } - }); - return symbols_4; + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); } else if (symbol.flags & 33554432 /* Transient */) { - var transient = symbol; - if (transient.leftSpread) { - return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); - } - if (transient.syntheticOrigin) { - return getRootSymbols(transient.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; } - return [symbol]; + return target; } // Emitter support function isArgumentsLocalBinding(node) { @@ -48543,7 +48875,7 @@ var ts; // AND // - binding is not declared in loop, should be renamed to avoid name reuse across siblings // let a, b - // { let x = 1; a = () => x; } + // { let x = 1; a = () => x; } // { let x = 100; b = () => x; } // console.log(a()); // should print '1' // console.log(b()); // should print '100' @@ -48786,20 +49118,20 @@ var ts; : unknownType; if (type.flags & 1024 /* UniqueESSymbol */ && type.symbol === symbol) { - flags |= 131072 /* AllowUniqueESSymbolType */; + flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 8192 /* AddUndefined */) { + if (flags & 131072 /* AddUndefined */) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -49399,9 +49731,6 @@ var ts; } } function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } if (typeParameters && typeParameters.length === 0) { var start = typeParameters.pos - "<".length; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; @@ -49485,6 +49814,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -49945,12 +50281,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); @@ -50144,7 +50483,7 @@ var ts; if (node.flags & 2097152 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } @@ -50409,7 +50748,7 @@ var ts; var node = createSynthesizedNode(71 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; - node.autoGenerateKind = 0 /* None */; + node.autoGenerateFlags = 0 /* None */; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -50424,22 +50763,24 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - /** Create a unique temporary variable. */ - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateFlags = 1 /* Auto */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + } return name; } ts.createTempVariable = createTempVariable; /** Create a unique temporary variable for use in a loop. */ function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateFlags = 2 /* Loop */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -50448,7 +50789,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateFlags = 3 /* Unique */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -50456,10 +50797,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4 /* Node */; + name.autoGenerateFlags = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; + } nextAutoGenerateId++; return name; } @@ -50757,11 +51100,12 @@ var ts; } ts.updateIndexSignature = updateIndexSignature; /* @internal */ - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -53624,13 +53968,13 @@ var ts; if (isLeftSideOfBinary) { // No need to parenthesize the left operand when the binary operator is // left associative: - // (a*b)/x -> a*b/x - // (a**b)/x -> a**b/x + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x // // Parentheses are needed for the left operand when the binary operator is // right associative: - // (a/b)**x -> (a/b)**x - // (a**b)**x -> (a**b)**x + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x return binaryOperatorAssociativity === 1 /* Right */; } else { @@ -53730,7 +54074,9 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || + emittedExpression.kind === 293 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -54380,6 +54726,7 @@ var ts; /// var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -54514,7 +54861,7 @@ var ts; switch (kind) { // Names case 71 /* Identifier */: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145 /* ComputedPropertyName */: @@ -54661,7 +55008,7 @@ var ts; case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217 /* ForOfStatement */: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219 /* BreakStatement */: @@ -55485,6 +55832,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -55584,7 +55932,12 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { // If the right-hand value of the destructuring assignment needs to be preserved (as // is the case when the destructuring assignment is part of a larger expression), // then we need to cache the right-hand value. @@ -55628,6 +55981,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -55655,6 +56028,15 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -56043,7 +56425,7 @@ var ts; */ var classAliases; /** - * Keeps track of whether we are within any containing namespaces when performing + * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; @@ -56740,11 +57122,14 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. @@ -58913,7 +59298,7 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -58927,6 +59312,7 @@ var ts; * just-in-time substitution for `super` expressions inside of async methods. */ var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -58964,6 +59350,83 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 215 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 216 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 217 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 264 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 208 /* Block */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 221 /* WithStatement */: + case 223 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } /** * Visits an AwaitExpression node. * @@ -59038,6 +59501,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -59050,10 +59580,17 @@ var ts; // `this` and `arguments` objects to `__awaiter`. The generator function // passed to `__awaiter` is executed inside of the callback to the // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -59069,27 +59606,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -59353,7 +59891,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); @@ -59365,8 +59903,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -59867,7 +60405,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncIterator) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -61050,7 +61588,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -62234,7 +62772,7 @@ var ts; ])); } /** - * Visits an ObjectLiteralExpression with computed propety names. + * Visits an ObjectLiteralExpression with computed property names. * * @param node An ObjectLiteralExpression node. */ @@ -66038,8 +66576,8 @@ var ts; // `throw` methods that step through the generator when invoked. // // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. // // variables: // _ Persistent state for the generator that is shared between the helper and the @@ -66331,7 +66869,7 @@ var ts; // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: @@ -66356,6 +66894,8 @@ var ts; ]))) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Transforms a SourceFile into a UMD module. @@ -66406,7 +66946,7 @@ var ts; // define(["require", "exports"], factory); // } // })(function ...) - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: @@ -66424,6 +66964,8 @@ var ts; ])) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Collect the additional asynchronous dependencies for the module. @@ -66475,6 +67017,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } /** * Transforms a SourceFile into an AMD or UMD module body. * @@ -66489,6 +67042,9 @@ var ts; } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); // Append the 'export =' statement if provided. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); @@ -66660,7 +67216,12 @@ var ts; ts.setEmitFlags(func, 8 /* CapturesThis */); } } - return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") @@ -66670,6 +67231,10 @@ var ts; // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } var func; if (languageVersion >= 2 /* ES2015 */) { func = ts.createArrowFunction( @@ -66696,6 +67261,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } /** * Visits an ImportDeclaration node. * @@ -66714,7 +67293,7 @@ var ts; if (namespaceDeclaration && !ts.isDefaultImport(node)) { // import * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { // import d from "mod"; @@ -66722,7 +67301,7 @@ var ts; // import d, { x, y } from "mod"; // import d, * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node))); @@ -67455,6 +68034,18 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); /// /// @@ -67472,6 +68063,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. @@ -68705,6 +69297,43 @@ var ts; if (hint === 1 /* Expression */) { return substituteExpression(node); } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 266 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } return node; } /** @@ -68895,9 +69524,11 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration( + var tslibImport = ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -69412,8 +70043,8 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { - // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { + // if file was external module this fact should be preserved in .d.ts as well. // in case if we didn't write any external module specifiers in .d.ts we need to emit something // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); @@ -69591,9 +70222,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 /* UseTypeOfFunction */ | - 16384 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -69607,7 +70238,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); errorNameNode = undefined; } } @@ -69845,12 +70476,15 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); write(";"); writeLine(); return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators + } if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -69938,6 +70572,7 @@ var ts; var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators write("export "); } if (modifiers & 512 /* Default */) { @@ -70079,6 +70714,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -70512,7 +71148,7 @@ var ts; // if this is property of type literal, // or is parameter of method/call/construct/index signature of type literal // emit only if type is specified - if (node.type) { + if (ts.hasType(node)) { write(": "); emitType(node.type); } @@ -70963,6 +71599,7 @@ var ts; // it allows emitSeparatedList to write separator appropriately) // Example: // original: function foo([, x, ,]) {} + // tslint:disable-next-line no-double-space // emit : function foo([ , x, , ]) {} write(" "); } @@ -71080,7 +71717,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -71370,9 +72007,9 @@ var ts; * @param tokenStartPos The start pos of the token. * @param emitCallback The callback used to emit the token. */ - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -71381,7 +72018,7 @@ var ts; if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { @@ -71406,7 +72043,7 @@ var ts; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -71847,7 +72484,6 @@ var ts; /// var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ /** @@ -71867,7 +72503,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -71876,7 +72515,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -72009,7 +72651,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -72075,16 +72717,29 @@ var ts; var generatedNames; // Set of names generated by the NameGenerator. var tempFlagsStack; // Stack of enclosing name generation scopes. var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { // public API printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, // internal API writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -72107,6 +72762,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -72122,6 +72781,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -72149,7 +72818,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -72175,6 +72844,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0 /* Auto */; + reservedNamesStack = []; comments.reset(); setWriter(/*output*/ undefined); } @@ -72238,7 +72908,9 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { @@ -72247,7 +72919,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -72485,7 +73157,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -72509,7 +73181,7 @@ var ts; case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: case 91 /* ImportKeyword */: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; // Expressions case 178 /* ArrayLiteralExpression */: @@ -72605,25 +73277,27 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); } } // // Identifiers // function emitIdentifier(node) { - write(getTextOfNode(node, /*includeTrivia*/ false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names // function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -72635,36 +73309,46 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } // // Signature elements // function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } // @@ -72673,19 +73357,19 @@ var ts; function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -72694,8 +73378,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -72707,13 +73391,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); + writeKeyword(node.kind === 154 /* GetAccessor */ ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -72722,34 +73407,37 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } // // Types // function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -72759,7 +73447,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -72781,34 +73471,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); @@ -72817,29 +73512,29 @@ var ts; emitList(node, node.types, 264 /* IntersectionTypeConstituents */); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -72847,23 +73542,24 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); @@ -72872,32 +73568,24 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); - write("}"); - } + writePunctuation("{"); + emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); - write("]"); - } + writePunctuation("["); + emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Expressions @@ -72934,7 +73622,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -72960,9 +73648,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -72970,26 +73658,27 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -73002,30 +73691,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -73049,7 +73742,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; @@ -73058,7 +73751,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -73086,12 +73779,12 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -73104,17 +73797,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } // @@ -73128,13 +73823,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; @@ -73143,27 +73838,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, node); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, node); + var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, node); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); + writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212 /* IfStatement */) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -73172,55 +73867,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -73234,58 +73937,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, /*contextNode*/ contextNode); + pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -73293,24 +74000,26 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos); - write(";"); + writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); + writeSemicolon(); } // // Declarations // function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { @@ -73319,9 +74028,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -73351,19 +74060,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: @@ -73396,7 +74105,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -73408,7 +74118,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, body); + writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -73433,17 +74143,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -73451,66 +74165,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* HeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* InterfaceMembers */); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81 /* EnumMembers */); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512 /* GlobalAugmentation */) { - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234 /* ModuleDeclaration */) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end); + writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71 /* Identifier */) { @@ -73522,23 +74247,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -73548,28 +74280,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -73578,14 +74326,16 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } @@ -73593,9 +74343,10 @@ var ts; // Module references // function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } // // JSX @@ -73606,14 +74357,14 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -73621,45 +74372,46 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -73674,13 +74426,15 @@ var ts; // Clauses // function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -73707,25 +74461,25 @@ var ts; } var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); - write(" "); + var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } @@ -73734,7 +74488,8 @@ var ts; // function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); // This is to ensure that we emit comment in the following case: // For example: // obj = { @@ -73752,13 +74507,15 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } @@ -73767,7 +74524,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Top-level nodes @@ -73865,33 +74622,60 @@ var ts; // // Helpers // + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328 /* Modifiers */); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); + } + } + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } } - function emitNodeWithPrefix(prefix, node, emit) { + function emitWithLeadingSpace(node) { if (node) { - write(prefix); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { - write(" "); + writeSpace(); emit(node); } else { @@ -73905,13 +74689,16 @@ var ts; emitList(parentNode, decorators, 24577 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360 /* Parameters */); + emitList(parentNode, parameters, 1296 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -73931,7 +74718,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -73946,6 +74733,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -73964,7 +74768,7 @@ var ts; return; } if (format & 7680 /* BracketsMask */) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -73975,7 +74779,7 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { - write(" "); + writeSpace(); } } else { @@ -73987,7 +74791,7 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } // Increase the indent, if requested. if (format & 64 /* Indented */) { @@ -73996,7 +74800,6 @@ var ts; // Emit each child. var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -74007,10 +74810,10 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new @@ -74023,7 +74826,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { - write(" "); + writeSpace(); } } // Emit this child. @@ -74046,7 +74849,7 @@ var ts; // Write a trailing comma, if requested. var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { - write(","); + writePunctuation(","); } // Emit any trailing comment of the last element in the list // i.e @@ -74054,7 +74857,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -74066,50 +74869,102 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -74300,6 +75155,7 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } /** * Pop the current name generation scope. @@ -74309,15 +75165,22 @@ var ts; return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } /** * Generate the text for a generated identifier. */ function generateName(name) { - if (name.autoGenerateKind === 4 /* Node */) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.skipNameGenerationScope) { + if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { var savedTempFlags = tempFlags; popNameGenerationScope(/*node*/ undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -74347,7 +75210,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } /** * Returns a value indicating whether a name is unique within a container. @@ -74369,11 +75233,14 @@ var ts; * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. */ - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 /* _i */ ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -74386,6 +75253,9 @@ var ts; ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -74478,11 +75348,11 @@ var ts; * Generates a unique identifier for a node. */ function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); } @@ -74500,7 +75370,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateFlags === 4 /* Node */ && node.autoGenerateId !== autoGenerateId) { break; } @@ -74511,17 +75381,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0 /* None */] = ""; - delimiters[16 /* CommaDelimited */] = ","; - delimiters[4 /* BarDelimited */] = " |"; - delimiters[8 /* AmpersandDelimited */] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28 /* DelimitersMask */]; - } function createBracketsMap() { var brackets = []; brackets[512 /* Braces */] = ["{", "}"]; @@ -74543,474 +75402,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - // Line separators - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - // Delimiters - ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; - ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; - ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; - ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; - // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; - // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; - // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; - ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - 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 changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - 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); }, - // Remove existing file info - onDeleteValue: removeExistingFileInfo, - // We will update in place instead of deleting existing value and adding new one - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - 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); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - 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); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - 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)]; - } - var seenFiles = ts.createMap(); - 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)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - 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]; - 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(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * @return {boolean} indicates if the shape signature has changed since last update. - */ - 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 = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Gets all files of the program excluding the default library file - */ - 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) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - 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 [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - // Changed if we had references - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - // If there are any new references that werent present previously there is change - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - // Otherwise its changed if there are more references previously than now - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - // Remove existing references - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - // add files referencing the removedFilePath, as changed files too - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - // Delete the entry for the removed file path - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.mapDefinedIter(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - }); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - 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(); - // Start with the paths this file was referenced by - var path = sourceFile.path; - 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); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - // Return array of values that needs emit - return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); /// /// /// -/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; @@ -75204,23 +75599,31 @@ var ts; return errorMessage; } ts.formatDiagnostic = formatDiagnostic; - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } - function formatAndReset(text, formatStyle) { + /** @internal */ + function formatColorAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } + ts.formatColorAndReset = formatColorAndReset; function padLeft(s, length) { while (s.length < length) { s = " " + s; @@ -75233,9 +75636,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -75248,7 +75651,7 @@ var ts; // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -75257,11 +75660,11 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += redForegroundEscapeSequence; + context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += ForegroundColorEscapeSequences.Red; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. @@ -75278,19 +75681,25 @@ var ts; } context += resetEscapeSequence; } - output += host.getNewLine(); - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + output += " - "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); output += context; } output += host.getNewLine(); } - return output; + return output + host.getNewLine(); } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { @@ -75558,7 +75967,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -75705,9 +76115,13 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); - if (resolutionToFile) { - // module used to be resolved to file - ignore it + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. return false; } var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); @@ -75860,7 +76274,7 @@ var ts; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); @@ -75964,24 +76378,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } // Create the emit resolver outside of the "emitTime" tracking code below. That way @@ -75992,7 +76408,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -76355,6 +76771,7 @@ var ts; // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -76544,7 +76961,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -76671,7 +77088,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { @@ -76908,13 +77325,13 @@ var ts; var emitFilePath = toPath(emitFileName); // Report error if the output overwrites input file if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { // The program is from either an inferred project or an external project - chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; // Report error if multiple files write into same file @@ -77010,6 +77427,35 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || + !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } } ts.createProgram = createProgram; /* @internal */ @@ -77235,6 +77681,7 @@ var ts; ScriptElementKindModifier["ambientModifier"] = "declare"; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -77754,7 +78201,7 @@ var ts; return isCompletedNode(n.thenStatement, sourceFile); case 211 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25 /* SemicolonToken */); + hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); case 178 /* ArrayLiteralExpression */: case 176 /* ArrayBindingPattern */: case 181 /* ElementAccessExpression */: @@ -77777,11 +78224,9 @@ var ts; return isCompletedNode(n.statement, sourceFile); case 213 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - var hasWhileKeyword = findChildOfKind(n, 106 /* WhileKeyword */, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); + return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) + : isCompletedNode(n.statement, sourceFile); case 163 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); case 190 /* TypeOfExpression */: @@ -77811,7 +78256,6 @@ var ts; return true; } } - ts.isCompletedNode = isCompletedNode; /* * Checks if node ends with 'expectedLastToken'. * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. @@ -77851,7 +78295,7 @@ var ts; } ts.hasChildOfKind = hasChildOfKind; function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); } ts.findChildOfKind = findChildOfKind; function findContainingList(node) { @@ -78042,8 +78486,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -78260,12 +78704,16 @@ var ts; ts.typeKeywords = [ 119 /* AnyKeyword */, 122 /* BooleanKeyword */, + 127 /* KeyOfKeyword */, 130 /* NeverKeyword */, + 95 /* NullKeyword */, 133 /* NumberKeyword */, 134 /* ObjectKeyword */, 136 /* StringKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, + 139 /* UndefinedKeyword */, + 140 /* UniqueKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -78286,6 +78734,28 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; + /** Add a value to a set, and return true if it wasn't already present. */ + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -78300,6 +78770,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -78309,8 +78780,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -78431,14 +78912,17 @@ var ts; /** * The default is CRLF. */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; + /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -78451,35 +78935,23 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { - return ts.getTextOfIdentifierOrLiteral(location); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && @@ -78493,12 +78965,16 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -78525,57 +79001,6 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; - function getOpenBrace(constructor, sourceFile) { - // First token is the open curly, this is where we want to put the 'super' call. - return constructor.body.getFirstToken(sourceFile); - } - ts.getOpenBrace = getOpenBrace; - function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); - } - ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; - function getSourceFileImportLocation(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); - var position = 0; - if (shebang !== undefined) { - position = shebang.length; - advancePastLineBreak(); - } - // For a source file, it is possible there are detached comments we should not skip - var ranges = ts.getLeadingCommentRanges(text, position); - if (!ranges) - return position; - // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end; - advancePastLineBreak(); - ranges = ranges.slice(1); - } - // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { - position = range.end; - advancePastLineBreak(); - continue; - } - break; - } - return position; - function advancePastLineBreak() { - if (position < text.length) { - var charCode = text.charCodeAt(position); - if (ts.isLineBreak(charCode)) { - position++; - if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { - position++; - } - } - } - } - } - ts.getSourceFileImportLocation = getSourceFileImportLocation; /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -78607,6 +79032,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ @@ -78849,8 +79278,8 @@ var ts; return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } // Set breakpoint on identifier element of destructuring pattern - // a or ...c or d: x from - // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || node.kind === 199 /* SpreadElement */ || node.kind === 265 /* PropertyAssignment */ || @@ -78992,8 +79421,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } @@ -79484,7 +79914,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -79493,8 +79923,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -79817,32 +80247,39 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. continue; - } - // for the ||||||| and ======== markers, add a comment for the first line, - // and then lex all subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); } } } @@ -80004,7 +80441,7 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } - // Special case < and > If they appear in a generic context they are punctuation, + // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then @@ -80114,11 +80551,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -80198,7 +80635,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -80233,37 +80670,20 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; + for (var path in paths) { var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); } } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } - } - }; - for (var path in paths) { - _loop_6(path); } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -80275,50 +80695,60 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - if (matches) { - var result = []; - // Trim away prefix and suffix - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + if (!host.readDirectory) { + return undefined; } - return undefined; + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + var directories = tryGetDirectories(host, baseDirectory); + // Trim away prefix and suffix + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module @@ -80390,10 +80820,12 @@ var ts; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -80405,31 +80837,38 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -80567,26 +81006,55 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } + if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) + && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { + return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); 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, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { + switch (completionData.kind) { + case 0 /* Data */: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1 /* JsDocTagName */: + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2 /* JsDocTag */: + // If the current position is a jsDoc tag, only tags should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3 /* JsDocParameterName */: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
completion list at "1" will contain "div" with type any + // var x =
+ // The completion list at "1" will contain "div" with type any var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -80596,37 +81064,37 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - // If the current position is a jsDoc tag name, only tag names should be provided for completion - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - // If the current position is a jsDoc tag, only tags should be provided for completion - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, 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, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if // - this is not a member completion list (all the keywords) // - other filters are enabled in required scenario so add those keywords + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -80634,14 +81102,9 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: "1" @@ -80649,12 +81112,30 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (includeInsertTextCompletions) { + if (origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + // TODO: GH#20619 Use configured quote style + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + } + } + if (insertText !== undefined && !includeInsertTextCompletions) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -80665,13 +81146,15 @@ var ts; // Use a 'sortText' of 0' so that all symbol completion entries come before any other // entries (like JavaScript identifier entries). return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -80682,103 +81165,119 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); - if (symbols) { - for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { - var symbol = symbols_5[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); - if (!entry) { - continue; - } - var name = entry.name; - if (uniques.has(name)) { - continue; - } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { - uniques.set(name, true); - } - entries.push(entry); + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + if (!entry) { + continue; } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); + } + entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9 /* StringLiteral */) { - return undefined; - } - if (node.parent.kind === 265 /* PropertyAssignment */ && - node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && - node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ - || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (isEqualityExpression(node.parent)) { - // Get completions from the type of the other operand - // i.e. switch (a) { - // case '/*completion position*/' - // } - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker); - } - else if (ts.isCaseOrDefaultClause(node.parent)) { - // Get completions from the type of the switch expression - // i.e. x === '/*completion position' - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.parent.parent.expression), typeChecker); + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + } + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174 /* LiteralType */: + switch (node.parent.parent.kind) { + case 160 /* TypeReference */: + // TODO: GH#21168 + return undefined; + case 172 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265 /* PropertyAssignment */: + if (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && + node.parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181 /* ElementAccessExpression */: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 249 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" - return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); + return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); } } function pathCompletionsInfo(entries) { @@ -80792,11 +81291,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80816,11 +81315,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccess(node, typeChecker, target, log) { - var type = typeChecker.getTypeAtLocation(node.expression); + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80837,6 +81335,30 @@ var ts; } return undefined; } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */, + kind: "label" /* label */, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768 /* TypeParameter */) { @@ -80866,29 +81388,33 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; } + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; // 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.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var typeChecker = program.getTypeChecker(); var name = entryId.name; // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); @@ -80896,26 +81422,26 @@ var ts; case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1 /* JsDocTagName */: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2 /* JsDocTag */: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; } case "none": { // Didn't find a symbol with this name. See if we can find a keyword instead. - if (ts.some(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; })) { + if (allKeywordsCompletions().some(function (c) { return c.name === name; })) { return { name: name, kind: "keyword" /* keyword */, @@ -80932,28 +81458,30 @@ var ts; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo && symbolOriginInfo.type === "export" + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); - var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { host: host, + program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), getCanonicalFileName: getCanonicalFileName, - symbolToken: undefined, + symbolToken: ts.tryCast(previousToken, ts.isIdentifier), kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, - }); + }).slice(0, 1); // Only take the first code action return { sourceDisplay: sourceDisplay, codeActions: codeActions }; } function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { @@ -80973,14 +81501,70 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getRecommendedCompletion(currentToken, checker /*, symbolToOriginInfoMap: SymbolOriginInfoMap*/) { - var ty = checker.getContextualType(currentToken); + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */ + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); + function getRecommendedCompletion(currentToken, checker) { + var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; // Don't include make a recommended completion for an abstract class return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) ? getFirstSymbolInChain(symbol, currentToken, checker) : undefined; } + function getContextualType(currentToken, checker) { + var parent = currentToken.parent; + switch (currentToken.kind) { + case 71 /* Identifier */: + return getContextualTypeFromParent(currentToken, checker); + case 58 /* EqualsToken */: + return ts.isVariableDeclaration(parent) ? checker.getContextualType(parent.initializer) : + ts.isBinaryExpression(parent) ? checker.getTypeAtLocation(parent.left) : undefined; + case 94 /* NewKeyword */: + return checker.getContextualType(parent); + case 73 /* CaseKeyword */: + return getSwitchedType(ts.cast(currentToken.parent, ts.isCaseClause), checker); + default: + return isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(currentToken); + } + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 183 /* NewExpression */: + return checker.getContextualType(parent); + case 195 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 261 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); if (chain) @@ -80991,7 +81575,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -81006,7 +81589,7 @@ var ts; if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } else { // When completion is requested without "@", we will have check to make sure that @@ -81027,7 +81610,7 @@ var ts; // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 /* JsDocTag */ }; } } } @@ -81037,7 +81620,7 @@ var ts; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); @@ -81050,24 +81633,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3 /* JsDocParameterName */, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0 /* None */, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - }; - } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available @@ -81092,9 +81660,11 @@ var ts; // Also determine whether we are trying to complete with members of that node // or attributes of a JSX tag. var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; + var isJsxInitializer = false; var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location @@ -81104,18 +81674,19 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 180 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144 /* QualifiedName */: + node = parent.left; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; } } else if (sourceFile.languageVariant === 1 /* JSX */) { @@ -81147,14 +81718,15 @@ var ts; location = contextToken; } break; + case 257 /* JsxAttribute */: + isJsxInitializer = previousToken.kind === 58 /* EqualsToken */; + break; } } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; var symbols = []; var symbolToOriginInfoMap = []; @@ -81169,8 +81741,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -81178,8 +81749,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -81190,8 +81760,8 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; + var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284 /* JSDocParameterTag */: @@ -81204,9 +81774,7 @@ var ts; } function getTypeScriptMemberSymbols() { // Right of dot member completion list - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2 /* PropertyAccess */; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); @@ -81251,10 +81819,9 @@ var ts; symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); } else { - // Filter private properties for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (typeChecker.isValidPropertyAccessForCompletions((node.parent), type, symbol)) { symbols.push(symbol); } } @@ -81275,13 +81842,16 @@ var ts; } if (tryGetConstructorLikeCompletionContainer(contextToken)) { // no members, only keywords - isMemberCompletion = false; + completionKind = 5 /* None */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter keywordFilters = 2 /* ConstructorParameterKeywords */; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3 /* FunctionLikeBodyKeywords */; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -81294,14 +81864,14 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return true; } } } // Get all entities in the current scope. - isMemberCompletion = false; + completionKind = 5 /* None */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -81335,40 +81905,55 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 /* SourceFile */ || - scopeNode.kind === 197 /* TemplateExpression */ || - scopeNode.kind === 260 /* JsxExpression */ || - scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1 /* Global */; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (options.includeInsertTextCompletions && scopeNode.kind !== 269 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269 /* SourceFile */: + case 197 /* TemplateExpression */: + case 260 /* JsxExpression */: + case 208 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { + var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + if (isTypeCompletion) + keywordFilters = 4 /* TypeKeywords */; 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)) { return true; } - // This is an alias, follow what it aliases - if (symbol && symbol.flags & 2097152 /* Alias */) { - symbol = typeChecker.getAliasedSymbol(symbol); - } + symbol = ts.skipAlias(symbol, typeChecker); // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); } - if (insideJsDocTagTypeExpression || - (!isContextTokenValueLocation(contextToken) && - (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + if (isTypeCompletion) { // Its a type, but you can reach it by namespace.type as well return symbolCanBeReferencedAtTypeLocation(symbol); } @@ -81398,6 +81983,7 @@ var ts; return parentKind === 203 /* AsExpression */; } } + return false; } function symbolCanBeReferencedAtTypeLocation(symbol) { symbol = symbol.exportSymbol || symbol; @@ -81418,27 +82004,21 @@ var ts; ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; - var name = symbol.name; // Don't add a completion for a re-export, only for the original. - // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } - var isDefaultExport = name === "default"; + var isDefaultExport = symbol.name === "default" /* Default */; if (isDefaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(symbol); - if (localSymbol) { - symbol = localSymbol; - name = localSymbol.name; - } - else { - name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); - } + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -81576,8 +82156,7 @@ var ts; */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { @@ -81602,7 +82181,7 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; if (!canGetType && rootDeclaration.kind === 147 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); @@ -81650,7 +82229,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -81667,7 +82246,7 @@ var ts; */ function getGetClassLikeCompletionSymbols(classLikeDeclaration) { // We're looking up possible property names from parent type. - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements @@ -81818,6 +82397,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -81987,7 +82581,10 @@ var ts; case "yield": return true; } - return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + && !(ts.isClassLike(contextToken.parent) && position > previousToken.end); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; @@ -82020,9 +82617,9 @@ var ts; existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" /* Default */; }); } - return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" /* Default */ && !existingImportsOrExports.get(e.escapedName); }); } /** * Filters out completion suggestions for named imports or exports. @@ -82146,88 +82743,69 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + // 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) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { return undefined; - // 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 (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; - } } - // If the symbol is for a member of an object type and is the internal name of an ES - // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - if (symbol.flags & 106500 /* ClassMember */) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 /* _ */ && - escapedName.charCodeAt(1) === 95 /* _ */ && - escapedName.charCodeAt(2) === 64 /* at */) { + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3 /* MemberLike */: return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - // TODO: GH#18169 - return allowStringLiteral ? JSON.stringify(name) : undefined; + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + case 5 /* None */: + case 1 /* Global */: + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - return name; } // A cache of completion entries for keywords, these do not change between sessions var _keywordCompletions = []; - function getKeywordCompletions(keywordFilter) { - var completions = _keywordCompletions[keywordFilter]; - if (completions) { - return completions; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); } - return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); - function generateKeywordCompletions(keywordFilter) { + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - return getAllKeywordCompletions(); + // "undefined" is a global variable, so don't need a keyword completion for it. + return kind !== 139 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: - return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + return isClassMemberCompletionKeyword(kind); case 2 /* ConstructorParameterKeywords */: - return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); - } - } - function getAllKeywordCompletions() { - var allKeywordsCompletions = []; - for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { - // "undefined" is a global variable, so don't need a keyword completion for it. - if (i === 139 /* UndefinedKeyword */) - continue; - allKeywordsCompletions.push({ - name: ts.tokenToString(i), - kind: "keyword" /* keyword */, - kindModifiers: "" /* none */, - sortText: "0" - }); + return isConstructorParameterCompletionKeyword(kind); + case 3 /* FunctionLikeBodyKeywords */: + return isFunctionLikeBodyCompletionKeyword(kind); + case 4 /* TypeKeywords */: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); } - return allKeywordsCompletions; - } - function getFilteredKeywordCompletions(filterFn) { - return ts.filter(getKeywordCompletions(0 /* None */), function (entry) { return filterFn(entry.name); }); - } + })); } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -82259,14 +82837,32 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } - function isEqualityExpression(node) { - return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + case 117 /* AbstractKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 139 /* UndefinedKeyword */: + return false; + } + return true; } function isEqualityOperatorKind(kind) { - return kind === 32 /* EqualsEqualsToken */ || - kind === 33 /* ExclamationEqualsToken */ || - kind === 34 /* EqualsEqualsEqualsToken */ || - kind === 35 /* ExclamationEqualsEqualsToken */; + switch (kind) { + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + return true; + default: + return false; + } } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { @@ -82300,8 +82896,7 @@ var ts; } /** * Gets all properties on a type, but if that type is a union of several types, - * tries to only include those types which declare properties, not methods. - * This ensures that we don't try providing completions for all the methods on e.g. Array. + * excludes array-like types or callable/constructable types. */ function getPropertiesForCompletion(type, checker, isForAccess) { if (!(type.flags & 131072 /* Union */)) { @@ -82323,11 +82918,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Note that getTouchingWord indicates failure by returning the sourceFile node. - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { @@ -82336,7 +82927,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -82346,8 +82937,8 @@ var ts; kind: "none" /* none */ }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -83142,7 +83733,7 @@ var ts; } function isNameMatch(name) { // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports - return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default"; + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; } } /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ @@ -83356,7 +83947,7 @@ var ts; // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = symbolName(importedSymbol); - if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { + if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } @@ -83420,7 +84011,7 @@ var ts; } FindAllReferences.getExportInfo = getExportInfo; function symbolName(symbol) { - if (symbol.escapedName !== "default") { + if (symbol.escapedName !== "default" /* Default */) { return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { @@ -83430,7 +84021,7 @@ var ts; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { - // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -83476,30 +84067,23 @@ var ts; FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); - if (!referencedSymbols || !referencedSymbols.length) { - return undefined; - } - var out = []; var checker = program.getTypeChecker(); - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - if (definition) { - out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }); - } - } - return out; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { // A node in a JSDoc comment can't have an implementation anyway. var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269 /* SourceFile */) { return undefined; } @@ -83519,7 +84103,7 @@ var ts; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -83527,14 +84111,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -83545,8 +84129,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_3 = def.node; var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_4 = def.node; @@ -83554,8 +84138,8 @@ var ts; } case "keyword": { var node_5 = def.node; - var name_6 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_6, kind: "keyword" /* keyword */, displayParts: [{ text: name_6, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case "this": { var node_6 = def.node; @@ -83673,10 +84257,11 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269 /* SourceFile */) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -83689,11 +84274,7 @@ var ts; // Could not find a symbol e.g. unknown identifier if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. - if (!options.implementations && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - // Can't have references to something that we have no symbol for. - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -83702,7 +84283,7 @@ var ts; } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleReferenceLocation(node) { - if (node.kind !== 9 /* StringLiteral */) { + if (node.kind !== 9 /* StringLiteral */ && node.kind !== 13 /* NoSubstitutionTemplateLiteral */) { return false; } switch (node.parent.kind) { @@ -83777,11 +84358,11 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); // Compute the meaning from the location and the symbol it references 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 state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, node, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); @@ -83805,8 +84386,22 @@ var ts; } return result; } + function getSpecialSearchKind(node) { + switch (node.kind) { + case 123 /* ConstructorKeyword */: + return 1 /* Constructor */; + case 71 /* Identifier */: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2 /* Class */; + } + // falls through + default: + return 0 /* None */; + } + } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -83815,18 +84410,29 @@ var ts; // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. return checker.getImmediateAliasedSymbol(symbol); } - return symbol; - } + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); /** * Holds all state needed for the finding references. * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { function State(sourceFiles, - /** True if we're searching for constructor references. */ - isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; - this.isForConstructor = isForConstructor; + this.specialSearchKind = specialSearchKind; this.checker = checker; this.cancellationToken = cancellationToken; this.searchMeaning = searchMeaning; @@ -83868,6 +84474,9 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); @@ -84180,11 +84789,18 @@ var ts; getReferenceForShorthandProperty(referenceSymbol, search, state); return; } - if (state.isForConstructor) { - findConstructorReferences(referenceLocation, sourceFile, search, state); - } - else { - addReference(referenceLocation, relatedSymbol, search.location, state); + switch (state.specialSearchKind) { + case 0 /* None */: + addReference(referenceLocation, relatedSymbol, search.location, state); + break; + case 1 /* Constructor */: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } @@ -84283,24 +84899,48 @@ var ts; } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ - function findConstructorReferences(referenceLocation, sourceFile, search, state) { + function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { addReference(referenceLocation, search.symbol, search.location, state); } - var pusher = state.referenceAdder(search.symbol, search.location); + var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. - findOwnConstructorReferences(search.symbol, sourceFile, pusher); + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } else { // If this class appears in `extends C`, then the extending class' "super" calls are references. var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); - if (classExtending && ts.isClassLike(classExtending)) { - findSuperConstructorAccesses(classExtending, pusher); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); } } } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, search.location, state); + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.parent.name === referenceLocation); + // This is the class declaration. + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + } + } + function addStaticThisReferences(classLike, pusher) { + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { + continue; + } + member.body.forEachChild(function cb(node) { + if (node.kind === 99 /* ThisKeyword */) { + pusher(node); + } + else if (!ts.isFunctionLike(node)) { + node.forEachChild(cb); + } + }); + } + } function getPropertyAccessExpressionFromRightHandSide(node) { return ts.isRightSideOfPropertyAccess(node) && node.parent; } @@ -84372,7 +85012,7 @@ var ts; var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { var parent = containingTypeReference.parent; - if (ts.isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) { + if (ts.hasType(parent) && parent.type === containingTypeReference && ts.hasInitializer(parent) && isImplementationExpression(parent.initializer)) { addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { @@ -84667,7 +85307,7 @@ var ts; // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol, location, checker, implementations) { // The search set contains at least the current symbol - var result = [symbol]; + var result = []; var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { // If the location is name of property symbol from object literal destructuring pattern @@ -84682,9 +85322,10 @@ var ts; // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - ts.addRange(result, checker.getRootSymbols(contextualSymbol)); - }); + for (var _i = 0, _a = getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker); _i < _a.length; _i++) { + var contextualSymbol = _a[_i]; + addRootSymbols(contextualSymbol); + } /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -84720,9 +85361,7 @@ var ts; // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { var rootSymbol = _a[_i]; - if (rootSymbol !== sym) { - result.push(rootSymbol); - } + result.push(rootSymbol); // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); @@ -84805,9 +85444,7 @@ var ts; // compare to our searchSymbol var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); - }); + var contextualSymbol = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), findRootSymbol); if (contextualSymbol) { return contextualSymbol; } @@ -84833,7 +85470,7 @@ var ts; function findRootSymbol(sym) { // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) // Or a union property, use its underlying unioned symbols - return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { // if it is in the list, then we are done if (search.includes(rootSymbol)) { return rootSymbol; @@ -84843,11 +85480,11 @@ var ts; // parent symbol if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { // Parents will only be defined if implementations is true - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })) { return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); return ts.find(result, search.includes); } return undefined; @@ -84867,26 +85504,11 @@ var ts; } /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { - var objectLiteral = node.parent; - var contextualType = checker.getContextualType(objectLiteral); + var contextualType = checker.getContextualType(node.parent); var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol = contextualType.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - if (contextualType.flags & 131072 /* Union */) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; + var symbol = contextualType && name && contextualType.getProperty(name); + return symbol ? [symbol] : + contextualType && contextualType.flags & 131072 /* Union */ ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -84921,14 +85543,12 @@ var ts; if (!node) { return false; } - else if (ts.isVariableLike(node)) { - if (node.initializer) { - return true; - } - else if (node.kind === 227 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } + else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { + return true; + } + else if (node.kind === 227 /* VariableDeclaration */) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } else if (ts.isFunctionLike(node)) { return !!node.body || ts.hasModifier(node, 2 /* Ambient */); @@ -85012,21 +85632,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - // Might still be on jsdoc, so keep looking. - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { @@ -85114,6 +85722,21 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -85121,26 +85744,14 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_6; - } - if (!type.symbol) { - return undefined; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -85184,59 +85795,29 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 123 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + if (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */ && symbol.flags & 32 /* Class */) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; - } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; + return undefined; } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -85286,6 +85867,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -85324,7 +85906,6 @@ var ts; (function (ts) { var JsDoc; (function (JsDoc) { - var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -85378,18 +85959,29 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289 /* JSDocPropertyTag */: + return [declaration]; + case 288 /* JSDocTypedefTag */: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; @@ -85420,10 +86012,13 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } /** @@ -85434,7 +86029,7 @@ var ts; function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -85515,9 +86110,16 @@ var ts; /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. - * Invalid positions are - * - within comments, strings (including template literals and regex), and JSXText - * - within a token + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations * * Hosts should ideally check that: * - The line is all whitespace up to 'position' before performing the insertion. @@ -85540,29 +86142,35 @@ var ts; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - // if climbing the tree did not find a declaration with parameters, complete to a single line comment - return singleLineTemplate; + return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.kind === 10 /* JsxText */) { + if (commentOwner.getStart() < position) { return undefined; } - if (commentOwner.getStart() < position || parameters.length === 0) { - // if climbing the tree found a declaration with parameters but the request was made inside it - // or if there are no parameters, complete to a single line comment - return singleLineTemplate; + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = parameters.map(function (_a, i) { - var name = _a.name; - var nameText = ts.isIdentifier(name) ? name.text : "param" + i; - var type = isJavaScriptFile ? "{any} " : ""; - return indentationStr + " * @param " + type + nameText + newLine; - }).join(""); + var docParams = ""; + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 /* Identifier */ ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } + } // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -85588,16 +86196,28 @@ var ts; case 151 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 149 /* PropertySignature */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 232 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; case 209 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; } case 269 /* SourceFile */: return undefined; + case 234 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 234 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 195 /* BinaryExpression */: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { @@ -85606,10 +86226,6 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } - case 10 /* JsxText */: { - var parameters_3 = ts.emptyArray; - return { commentOwner: commentOwner, parameters: parameters_3 }; - } } } } @@ -85815,8 +86431,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_7.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -85947,7 +86563,7 @@ var ts; if (!shouldKeepItem(declaration, checker)) { continue; } - // It was a match! If the pattern has dots in it, then also see if the + // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. var containerMatches = matches; if (patternMatcher.patternContainsDots) { @@ -85976,8 +86592,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -86046,8 +86662,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -87692,7 +88308,7 @@ var ts; // import "mod"; // import d from "mod" // import {a as A } from "mod"; - // import * as NS from "mod" + // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); // import("mod"); @@ -87792,9 +88408,16 @@ var ts; symbol.parent.flags & 1536 /* Module */) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9 /* StringLiteral */) { @@ -88028,7 +88651,7 @@ var ts; function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may // also just have nodes without commas. For example "Foo(a b c)" will have 3 - // args without commas. We want to find what index we're at. So we count + // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. // @@ -88054,12 +88677,12 @@ var ts; // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there - // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // is a small subtlety. If you have "Foo(a,)", then the child list will just have // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); @@ -88080,9 +88703,11 @@ var ts; // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // + // tslint:disable no-double-space // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -88129,9 +88754,8 @@ var ts; // Otherwise, we will not show signature help past the expression. // For example, // - // ` ${ 1 + 1 foo(10) - // | | - // + // ` ${ 1 + 1 foo(10) + // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 197 /* TemplateExpression */) { @@ -88173,6 +88797,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -88188,14 +88813,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88203,7 +88834,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -88224,7 +88863,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -88235,7 +88875,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -88350,13 +88991,17 @@ var ts; return "" /* unknown */; } function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) : "" /* none */; + var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ? + "optional" /* optionalModifier */ + : "" /* none */; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -88366,6 +89011,8 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var printer; + var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -88433,14 +89080,14 @@ var ts; displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -88481,6 +89128,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) @@ -88496,14 +89144,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -88511,10 +89159,10 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); @@ -88524,7 +89172,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); @@ -88532,7 +89180,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); @@ -88560,12 +89208,12 @@ var ts; else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example - // type list = T[]; // Both T will go through same code path + // type list = T[]; // Both T will go through same code path addInPrefix(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -88590,7 +89238,23 @@ var ts; } } if (symbolFlags & 2097152 /* Alias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -88636,7 +89300,7 @@ var ts; if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); } else { @@ -88653,7 +89317,8 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -88704,26 +89369,45 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias" /* alias */); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92 /* InKeyword */)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); - if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -88746,7 +89430,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88761,7 +89445,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -89275,8 +89960,12 @@ var ts; for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); @@ -89306,7 +89995,7 @@ var ts; // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator @@ -89324,17 +90013,17 @@ var ts; rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace + // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // For functions and control block place } on a new line [multi-line rule] rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), // Space/new line after }. @@ -89421,7 +90110,7 @@ var ts; rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), // decorators - rule("SpaceBeforeAt", anyToken, 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ @@ -89447,8 +90136,8 @@ var ts; // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2 /* Space */), - rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8 /* Delete */), + rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), // Insert space after function keyword for anonymous functions rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), @@ -89503,8 +90192,10 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; - // These rules are lower in priority than user-configurable + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), @@ -89512,13 +90203,13 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - // No space before and after indexer - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2 /* Space */), + rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; @@ -89608,6 +90299,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 /* PropertyDeclaration */ || + contextKind === 149 /* PropertySignature */ || + contextKind === 147 /* Parameter */ || + contextKind === 227 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196 /* ConditionalExpression */; } @@ -89753,11 +90455,11 @@ var ts; function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } - function isNonJsxElementContext(context) { - return context.contextNode.kind !== 250 /* JsxElement */; + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 250 /* JsxElement */ && context.contextNode.kind !== 254 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 260 /* JsxExpression */; + return context.contextNode.kind === 260 /* JsxExpression */ || context.contextNode.kind === 259 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { return context.nextTokenParent.kind === 257 /* JsxAttribute */; @@ -90279,29 +90981,32 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1 /* Unknown */) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -90335,67 +91040,55 @@ var ts; case 18 /* CloseBraceToken */: case 22 /* CloseBracketToken */: case 20 /* CloseParenToken */: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - // if this token is the first token following the list of decorators, we do not need to indent - return indentation; - } - } - switch (kind) { - // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: - return indentation; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: { - if (container.kind === 252 /* JsxOpeningElement */ || - container.kind === 253 /* JsxClosingElement */ || - container.kind === 251 /* JsxSelfClosingElement */) { - return indentation; - } - break; - } - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: { - if (container.kind !== 173 /* MappedType */) { - return indentation; - } - break; - } - } - // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 17 /* OpenBraceToken */: + case 18 /* CloseBraceToken */: + case 19 /* OpenParenToken */: + case 20 /* CloseParenToken */: + case 82 /* ElseKeyword */: + case 106 /* WhileKeyword */: + case 57 /* AtToken */: + return false; + case 41 /* SlashToken */: + case 29 /* GreaterThanToken */: + switch (container.kind) { + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: + return false; + } + break; + case 21 /* OpenBracketToken */: + case 22 /* CloseBracketToken */: + if (container.kind !== 173 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; } @@ -90418,7 +91111,7 @@ var ts; // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes - // such tokens will be consumed in processChildNode for for the child that follows them + // such tokens will be consumed in processChildNode for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { @@ -90640,23 +91333,25 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0 /* None */; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAction = 2 /* LineRemoved */; - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); - } - } - else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAction = 1 /* LineAdded */; - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -90804,14 +91499,16 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1 /* Ignore */: // no action required - return; + return 0 /* None */; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } break; case 4 /* NewLine */: @@ -90819,25 +91516,27 @@ var ts; // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } - break; } + return 0 /* None */; } } var LineAction; @@ -90850,7 +91549,7 @@ var ts; * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword - tokenAtPosition, predicate) { + tokenAtPosition, predicate) { if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { @@ -90949,12 +91648,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -90964,20 +91663,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -91297,11 +91989,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1 /* Unknown */; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: @@ -91421,6 +92115,7 @@ var ts; case 176 /* ArrayBindingPattern */: case 175 /* ObjectBindingPattern */: case 252 /* JsxOpeningElement */: + case 255 /* JsxOpeningFragment */: case 251 /* JsxSelfClosingElement */: case 260 /* JsxExpression */: case 151 /* MethodSignature */: @@ -91466,6 +92161,8 @@ var ts; (!!child.namedBindings && child.namedBindings.kind !== 242 /* NamedImports */); case 250 /* JsxElement */: return childKind !== 253 /* JsxClosingElement */; + case 254 /* JsxFragment */: + return childKind !== 256 /* JsxClosingFragment */; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -91631,10 +92328,13 @@ var ts; this.formatContext = formatContext; this.validator = validator; this.changes = []; + this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + // Map from class id to nodes to insert at the start + this.nodesInsertedAtClassStarts = ts.createMap(); this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -91649,14 +92349,14 @@ var ts; if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -91673,6 +92373,9 @@ var ts; this.deleteNode(sourceFile, node); return this; } + var id = ts.getNodeId(node); + ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); + this.deletedNodesInLists[id] = true; if (index !== containingList.length - 1) { var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { @@ -91686,9 +92389,17 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); + var prev = containingList[index - 1]; + if (this.deletedNodesInLists[ts.getNodeId(prev)]) { + var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + var end = getAdjustedEndPosition(sourceFile, node, {}); + this.deleteRange(sourceFile, { pos: pos, end: end }); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); + if (previousToken && isSeparator(node, previousToken)) { + this.deleteNodeRange(sourceFile, previousToken, node); + } } } return this; @@ -91730,37 +92441,93 @@ var ts; }); return this; }; - ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); - }; - ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes) { + this.replaceWithMultiple(sourceFile, oldNode.getStart(sourceFile), oldNode.getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; - ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); - }; - ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes) { + this.replaceWithMultiple(sourceFile, ts.first(oldNodes).getStart(sourceFile), ts.last(oldNodes).getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; - ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); }; - ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { - if (options === void 0) { options = {}; } - if ((ts.isStatementButNotDeclaration(after)) || + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { + var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { + return { suffix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var startPosition = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + var firstMember = ts.firstOrUndefined(cls.members); + if (!firstMember) { + var id = ts.getNodeId(cls).toString(); + var newMembers = this.nodesInsertedAtClassStarts.get(id); + if (newMembers) { + ts.Debug.assert(newMembers.sourceFile === sourceFile && newMembers.cls === cls); + newMembers.members.push(newElement); + } + else { + this.nodesInsertedAtClassStarts.set(id, { sourceFile: sourceFile, cls: cls, members: [newElement] }); + } + } + else { + this.insertNodeBefore(sourceFile, firstMember, newElement); + } + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + if (ts.isStatementButNotDeclaration(after) || after.kind === 150 /* PropertyDeclaration */ || after.kind === 149 /* PropertySignature */ || after.kind === 151 /* MethodSignature */) { @@ -91776,8 +92543,20 @@ var ts; }); } } - var endPosition = getAdjustedEndPosition(sourceFile, after, options); - return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, this.getInsertNodeAfterOptions(after)); + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + } + else if (ts.isStatement(node) || ts.isClassElement(node) || ts.isTypeElement(node)) { + return { suffix: this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(node)) { + return { prefix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -91918,8 +92697,19 @@ var ts; } return this; }; + ChangeTracker.prototype.finishInsertNodeAtClassStart = function () { + var _this = this; + this.nodesInsertedAtClassStarts.forEach(function (_a) { + var sourceFile = _a.sourceFile, cls = _a.cls, members = _a.members; + var newCls = cls.kind === 230 /* ClassDeclaration */ + ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) + : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); + _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + }); + }; ChangeTracker.prototype.getChanges = function () { var _this = this; + this.finishInsertNodeAtClassStart(); var changesPerFile = ts.createMap(); // group changes per file for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { @@ -92099,6 +92889,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -92137,12 +92959,53 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; }()); + function getInsertionPositionAtSourceFileTop(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -92150,24 +93013,33 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var codeFixes = []; - function registerCodeFix(codeFix) { - ts.forEach(codeFix.errorCodes, function (error) { - var fixes = codeFixes[error]; - if (!fixes) { - fixes = []; - codeFixes[error] = fixes; - } - fixes.push(codeFix); - }); + var codeFixRegistrations = []; + var fixIdToRegistration = ts.createMap(); + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + var registrations = codeFixRegistrations[error]; + if (!registrations) { + registrations = []; + codeFixRegistrations[error] = registrations; + } + registrations.push(reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } } codefix.registerCodeFix = registerCodeFix; function getSupportedErrorCodes() { - return Object.keys(codeFixes); + return Object.keys(codeFixRegistrations); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; function getFixes(context) { - var fixes = codeFixes[context.errorCode]; + var fixes = codeFixRegistrations[context.errorCode]; var allActions = []; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); @@ -92186,6 +93058,42 @@ var ts; return allActions; } codefix.getFixes = getFixes; + function getAllFixes(context) { + // Currently fixId is always a string. + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); + }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function codeFixAllWithTextChanges(context, errorCodes, use) { + var changes = []; + eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); + changes.sort(function (a, b) { return b.span.start - a.span.start; }); + return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); + } + codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92196,14 +93104,15 @@ var ts; // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - return ts.flatMapIter(refactors.values(), function (refactor) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); - }); + })); } refactor_1.getApplicableRefactors = getApplicableRefactors; function getEditsForRefactor(context, refactorName, actionName) { @@ -92222,22 +93131,24 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var decorator = ts.getAncestor(token, 148 /* Decorator */); - ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); - var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, decorator.expression, replacement); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), - changes: changeTracker.getChanges() - }]; - } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92245,27 +93156,36 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var qualifiedName = ts.getAncestor(token, 144 /* QualifiedName */); - ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); - if (!ts.isIdentifier(qualifiedName.left)) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); } - var leftText = qualifiedName.left.getText(sourceFile); - var rightText = qualifiedName.right.getText(sourceFile); - var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, qualifiedName, replacement); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), - changes: changeTracker.getChanges() - }]; - } + }); }, }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92273,55 +93193,61 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code], - getCodeActions: getActionForClassLikeIncorrectImplementsInterface + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); + if (changes.length === 0) + return undefined; + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); + return { description: description, changes: changes, fixId: fixId }; + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + } + } + }); + }, }); - function getActionForClassLikeIncorrectImplementsInterface(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var classDeclaration = ts.getContainingClass(token); - if (!classDeclaration) { - return undefined; - } - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); + function getClass(sourceFile, pos) { + var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)); + ts.Debug.assert(!!classDeclaration); + return classDeclaration; + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); var classType = checker.getTypeAtLocation(classDeclaration); - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(classDeclaration); - var hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, 1 /* Number */); - var hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, 0 /* String */); - var result = []; - for (var _i = 0, implementedTypeNodes_2 = implementedTypeNodes; _i < implementedTypeNodes_2.length; _i++) { - var implementedTypeNode = implementedTypeNodes_2[_i]; - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - var implementedType = checker.getTypeAtLocation(implementedTypeNode); - var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); - var newNodes = []; - createAndAddMissingIndexSignatureDeclaration(implementedType, 1 /* Number */, hasNumericIndexSignature, newNodes); - createAndAddMissingIndexSignatureDeclaration(implementedType, 0 /* String */, hasStringIndexSignature, newNodes); - newNodes = newNodes.concat(codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker)); - var message = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - if (newNodes.length > 0) { - pushAction(result, newNodes, message); - } + if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - return result; - function createAndAddMissingIndexSignatureDeclaration(type, kind, hasIndexSigOfKind, newNodes) { - if (hasIndexSigOfKind) { - return; - } + if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); - if (!indexInfoOfKind) { - return; + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); } - var newIndexSignatureDeclaration = checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration); - newNodes.push(newIndexSignatureDeclaration); - } - function pushAction(result, newNodes, description) { - result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -92331,158 +93257,176 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ]; + var fixId = "addMissingMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, - ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], - getCodeActions: getActionsForAddMissingMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var addMember = inJs ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenNames = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var program = context.program; + var info = getInfo(diag.file, diag.start, program.getTypeChecker()); + if (!info) + return; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + if (!ts.addToSeen(seenNames, token.text)) { + return; + } + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + } + else { + if (inJs) { + addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); + addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + } + } + }); + }, }); - function getActionsForAddMissingMember(context) { - var tokenSourceFile = context.sourceFile; - var start = context.span.start; + function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(tokenSourceFile, start, /*includeJsDocComment*/ false); - if (token.kind !== 71 /* Identifier */) { + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false); + if (!ts.isIdentifier(token)) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent)) { + var classAndMakeStatic = getClassAndMakeStatic(token, checker); + if (!classAndMakeStatic) { + return undefined; + } + var classDeclaration = classAndMakeStatic.classDeclaration, makeStatic = classAndMakeStatic.makeStatic; + var classDeclarationSourceFile = classDeclaration.getSourceFile(); + var inJs = ts.isInJavaScriptFile(classDeclarationSourceFile); + var call = ts.tryCast(token.parent.parent, ts.isCallExpression); + return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; + } + function getClassAndMakeStatic(token, checker) { + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) { return undefined; } - var tokenName = token.getText(tokenSourceFile); - var makeStatic = false; - var classDeclaration; - if (token.parent.expression.kind === 99 /* ThisKeyword */) { + if (parent.expression.kind === 99 /* ThisKeyword */) { var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); if (!ts.isClassElement(containingClassMemberDeclaration)) { return undefined; } - classDeclaration = containingClassMemberDeclaration.parent; + var classDeclaration = containingClassMemberDeclaration.parent; // Property accesses on `this` in a static method are accesses of a static member. - makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */); + return ts.isClassLike(classDeclaration) ? { classDeclaration: classDeclaration, makeStatic: ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */) } : undefined; } else { - var checker = context.program.getTypeChecker(); - var leftExpression = token.parent.expression; - var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 65536 /* Object */) { - var symbol = leftExpressionType.symbol; - if (symbol.flags & 32 /* Class */) { - classDeclaration = symbol.declarations && symbol.declarations[0]; - if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { - // The expression is a class symbol but the type is not the instance-side. - makeStatic = true; - } - } + var leftExpressionType = checker.getTypeAtLocation(parent.expression); + var symbol = leftExpressionType.symbol; + if (!(leftExpressionType.flags & 65536 /* Object */ && symbol.flags & 32 /* Class */)) { + return undefined; } + var classDeclaration = ts.cast(ts.first(symbol.declarations), ts.isClassLike); + // The expression is a class symbol but the type is not the instance-side. + return { classDeclaration: classDeclaration, makeStatic: leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol) }; } - if (!classDeclaration || !ts.isClassLike(classDeclaration)) { + } + function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + if (changes.length === 0) return undefined; - } - var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); - var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); - return ts.isInJavaScriptFile(classDeclarationSourceFile) ? - getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : - getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); - function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ false); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - if (makeStatic) { - if (classDeclaration.kind === 200 /* ClassExpression */) { - return actions; - } - var className = classDeclaration.name.getText(); - var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); - var initializeStaticAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), - changes: staticInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeStaticAction); - return actions; - } - else { - var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); - if (!classConstructor) { - return actions; - } - var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); - var initializeAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), - changes: propertyInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeAction); - return actions; - } - } - function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ true); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - var typeNode; - if (token.parent.parent.kind === 195 /* BinaryExpression */) { - var binaryExpression = token.parent.parent; - var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); - } - typeNode = typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); - var property = ts.createProperty( - /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, - /*questionToken*/ undefined, typeNode, - /*initializer*/ undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; - actions = ts.append(actions, { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: propertyChangeTracker.getChanges() - }); - if (!makeStatic) { - // Index signatures cannot have the static modifier. - var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); - var indexingParameter = ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, "x", - /*questionToken*/ undefined, stringTypeNode, - /*initializer*/ undefined); - var indexSignature = ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); - actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), - changes: indexSignatureChangeTracker.getChanges() - }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); + return { description: description, changes: changes, fixId: fixId }; + } + function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 200 /* ClassExpression */) { + return; } - return actions; + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); } - function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 182 /* CallExpression */) { - var callExpression = token.parent.parent; - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: methodDeclarationChangeTracker.getChanges() - }; + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); } } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 195 /* BinaryExpression */) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + } + return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + } + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92490,18 +93434,35 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], - getCodeActions: getActionsForCorrectSpelling + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context.program.getTypeChecker()); + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion); + }); }, }); - function getActionsForCorrectSpelling(context) { - var sourceFile = context.sourceFile; + function getInfo(sourceFile, pos, checker) { // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 - var checker = context.program.getTypeChecker(); + var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852 var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 71 /* Identifier */); @@ -92514,18 +93475,10 @@ var ts; ts.Debug.assert(name !== undefined, "name should be defined"); suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - if (suggestion) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: node.getStart(), length: node.getWidth() }, - newText: suggestion - }], - }], - }]; - } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); } function convertSemanticMeaningToSymbolFlags(meaning) { var flags = 0; @@ -92547,31 +93500,39 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixCannotFindModule"; + var errorCodes = [ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, - ], + errorCodes: errorCodes, 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, sourceFile.fileName, token.text); - return action && [action]; + var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); + return codeAction && [__assign({ fixId: fixId }, codeAction)]; }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { + var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + if (pkg) { + commands.push(getCommand(diag.file.fileName, pkg)); + } + }); }, }); - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + function getModuleName(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; + } + function getCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function getTypesPackageNameToInstall(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: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + // If !registry, registry not available yet, can't do anything. + return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; + } + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = getTypesPackageNameToInstall(host, moduleName); + return packageName === undefined ? undefined : { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), changes: [], - commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + commands: [getCommand(fileName, packageName)], }; } codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; @@ -92582,44 +93543,45 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code], - getCodeActions: getActionForClassLikeMissingAbstractMember - }); - codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code], - getCodeActions: getActionForClassLikeMissingAbstractMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + }); + return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); + }); }, }); - function getActionForClassLikeMissingAbstractMember(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; + function getClass(sourceFile, pos) { // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - if (ts.isClassLike(token.parent)) { - var classDeclaration = token.parent; - var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); - var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - var extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType); - var abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember); - var newNodes = codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker); - var changes = codefix.newNodesToChanges(newNodes, ts.getOpenBraceOfClassLike(classDeclaration, sourceFile), context); - if (changes && changes.length > 0) { - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), - changes: changes - }]; - } - } - return undefined; + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var classDeclaration = token.parent; + ts.Debug.assert(ts.isClassLike(classDeclaration)); + return classDeclaration; + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { - var decls = symbol.getDeclarations(); - ts.Debug.assert(!!(decls && decls.length > 0)); - var flags = ts.getModifierFlags(decls[0]); + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -92629,48 +93591,54 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 99 /* ThisKeyword */) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) return undefined; - } - var constructor = ts.getContainingFunction(token); - var superCall = findSuperCall(constructor.body); - if (!superCall) { - return undefined; - } - // figure out if the `this` access is actually inside the supercall - // i.e. super(this.a), since in that case we won't suggest a fix - if (superCall.expression && superCall.expression.kind === 182 /* CallExpression */) { - var expressionArguments = superCall.expression.arguments; - for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { - var arg = expressionArguments_1[_i]; - if (arg.expression === token) { - return undefined; - } - } - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); - changeTracker.deleteNode(sourceFile, superCall); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), - changes: changeTracker.getChanges() - }]; - function findSuperCall(n) { - if (n.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { - return n; - } - if (ts.isFunctionLike(n)) { - return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); // Ensure we only do this once per class. + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); } - return ts.forEachChild(n, findSuperCall); - } - } + }); + }, }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.deleteNode(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 99 /* ThisKeyword */); + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92678,23 +93646,30 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 123 /* ConstructorKeyword */) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), - changes: changeTracker.getChanges() - }]; - } + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92702,40 +93677,51 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var classDeclNode = ts.getContainingClass(token); - if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceRange(sourceFile, { pos: extendsToken.getStart(), end: extendsToken.end }, ts.createToken(108 /* ImplementsKeyword */)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === 85 /* ExtendsKeyword */ && + heritageClauses[1].token === 108 /* ImplementsKeyword */) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */)); + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; } - var heritageClauses = classDeclNode.heritageClauses; - if (!(heritageClauses && heritageClauses.length > 0)) { - return undefined; - } - var extendsToken = heritageClauses[0].getFirstToken(); - if (!(extendsToken && extendsToken.kind === 85 /* ExtendsKeyword */)) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); - // We replace existing keywords with commas. - for (var i = 1; i < heritageClauses.length; i++) { - var keywordToken = heritageClauses[i].getFirstToken(); - if (keywordToken) { - changeTracker.replaceNode(sourceFile, keywordToken, ts.createToken(26 /* CommaToken */)); - } - } - var result = [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), - changes: changeTracker.getChanges() - }]; - return result; + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); } - }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92743,22 +93729,27 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var errorCodes = [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 71 /* Identifier */) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), - changes: changeTracker.getChanges() - }]; - } + var token = getNode(sourceFile, context.span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isIdentifier); + } + function doChange(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92766,183 +93757,311 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, - ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - // this handles var ["computed"] = 12; - if (token.kind === 21 /* OpenBracketToken */) { - token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); + var token = getToken(sourceFile, context.span.start); + var result = []; + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + if (deletion.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); + result.push({ description: description, changes: deletion, fixId: fixIdDelete }); } - switch (token.kind) { - case 71 /* Identifier */: - return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); - case 150 /* PropertyDeclaration */: - case 241 /* NamespaceImport */: - return [deleteNode(token.parent)]; + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + if (prefix.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); + result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = getToken(diag.file, diag.start); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + tryDeleteDeclaration(changes, sourceFile, token); + break; default: - return deleteDefault(); + ts.Debug.fail(JSON.stringify(context.fixId)); } - function deleteDefault() { - if (ts.isDeclarationName(token)) { - return [deleteNode(token.parent)]; + }); }, + }); + function getToken(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + // this handles var ["computed"] = 12; + return token.kind === 21 /* OpenBracketToken */ ? ts.getTokenAtPosition(sourceFile, pos + 1, /*includeJsDocComment*/ false) : token; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + // Don't offer to prefix a property. + if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 147 /* Parameter */: + return true; + case 227 /* VariableDeclaration */: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 217 /* ForOfStatement */: + case 216 /* ForInStatement */: + return true; } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return [deleteNode(token.parent.parent)]; + } + } + return false; + } + function tryDeleteDeclaration(changes, sourceFile, token) { + switch (token.kind) { + case 71 /* Identifier */: + tryDeleteIdentifier(changes, sourceFile, token); + break; + case 150 /* PropertyDeclaration */: + case 241 /* NamespaceImport */: + changes.deleteNode(sourceFile, token.parent); + break; + default: + tryDeleteDefault(changes, sourceFile, token); + } + } + function tryDeleteDefault(changes, sourceFile, token) { + if (ts.isDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent.parent); + } + } + function tryDeleteIdentifier(changes, sourceFile, identifier) { + var parent = identifier.parent; + switch (parent.kind) { + case 227 /* VariableDeclaration */: + tryDeleteVariableDeclaration(changes, sourceFile, parent); + break; + case 146 /* TypeParameter */: + var typeParameters = parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + changes.deleteNodeRange(sourceFile, previousToken, nextToken); } else { - return undefined; + changes.deleteNodeInList(sourceFile, parent); } - } - function prefixIdentifierWithUnderscore(identifier) { - var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), - changes: [{ - fileName: sourceFile.path, - textChanges: [{ - span: { start: startPosition, length: 0 }, - newText: "_" - }] - }] - }; - } - function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { - var parent = identifier.parent; - switch (parent.kind) { - case 227 /* VariableDeclaration */: - return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 146 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - return [deleteNodeRange(previousToken, nextToken)]; - } - else { - return [deleteNodeInList(parent)]; - } - case 147 /* Parameter */: - var functionDeclaration = parent.parent; - var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); - return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ? [deleteAction] - : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; - // handle case where 'import a = A;' - case 238 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); - return [deleteNode(importEquals)]; - case 243 /* ImportSpecifier */: - var namedImports = parent.parent; - if (namedImports.elements.length === 1) { - return deleteNamedImportBinding(namedImports); - } - else { - // delete import specifier - return [deleteNodeInList(parent)]; - } - case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' - var importClause = parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 239 /* ImportDeclaration */); - return [deleteNode(importDecl)]; - } - else { - // import |d,| * as ns from './file' - var start_6 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; - } - else { - return [deleteNode(importClause.name)]; - } - } - case 241 /* NamespaceImport */: - return deleteNamedImportBinding(parent); - default: - return deleteDefault(); + break; + case 147 /* Parameter */: + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } - } - function deleteNamedImportBinding(namedBindings) { - if (namedBindings.parent.name) { - // Delete named imports while preserving the default import - // import d|, * as ns| from './file' - // import d|, { a }| from './file' - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; - } - return undefined; + else { + changes.deleteNodeInList(sourceFile, parent); + } + break; + // handle case where 'import a = A;' + case 238 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); + changes.deleteNode(sourceFile, importEquals); + break; + case 243 /* ImportSpecifier */: + var namedImports = parent.parent; + if (namedImports.elements.length === 1) { + tryDeleteNamedImportBinding(changes, sourceFile, namedImports); } else { - // Delete the entire import declaration - // |import * as ns from './file'| - // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); - return [deleteNode(importDecl)]; + // delete import specifier + changes.deleteNodeInList(sourceFile, parent); } - } - // token.parent is a variableDeclaration - function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { - switch (varDecl.parent.parent.kind) { - case 215 /* ForStatement */: - var forStatement = varDecl.parent.parent; - var forInitializer = forStatement.initializer; - return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 217 /* ForOfStatement */: - var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); - var forOfInitializer = forOfStatement.initializer; - return [ - replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), - prefixIdentifierWithUnderscore(identifier) - ]; - case 216 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return [prefixIdentifierWithUnderscore(identifier)]; - default: - var variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return [deleteNode(variableStatement)]; - } - else { - return [deleteNodeInList(varDecl)]; - } + break; + case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + var importClause = parent; + if (!importClause.namedBindings) { + changes.deleteNode(sourceFile, ts.getAncestor(importClause, 239 /* ImportDeclaration */)); } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + changes.deleteNode(sourceFile, importClause.name); + } + } + break; + case 241 /* NamespaceImport */: + tryDeleteNamedImportBinding(changes, sourceFile, parent); + break; + default: + tryDeleteDefault(changes, sourceFile, identifier); + break; + } + } + function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) { + if (namedBindings.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); } - function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); - } - function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); - } - function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); - } - function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); + changes.deleteNode(sourceFile, importDecl); + } + } + // token.parent is a variableDeclaration + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + switch (varDecl.parent.parent.kind) { + case 215 /* ForStatement */: { + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + changes.deleteNode(sourceFile, forInitializer); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + break; } - function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); + case 217 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); + break; + case 216 /* ForInStatement */: + case 225 /* TryStatement */: + break; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + changes.deleteNode(sourceFile, variableStatement); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain)]; + if (typeNode.kind === 274 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); } - function makeChange(changeTracker) { + return actions; + function fix(type, fixId) { + var newText = typeString(type, checker); return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], + fixId: fixId, }; } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 274 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + }); } }); + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function createChange(declaration, sourceFile, newText) { + return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; + } + function typeString(type, checker) { + return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); + } + function isTypeContainer(node) { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case 203 /* AsExpression */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 229 /* FunctionDeclaration */: + case 154 /* GetAccessor */: + case 158 /* IndexSignature */: + case 173 /* MappedType */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 155 /* SetAccessor */: + case 232 /* TypeAliasDeclaration */: + case 185 /* TypeAssertionExpression */: + case 227 /* VariableDeclaration */: + return true; + default: + return false; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92950,62 +94069,72 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], - getCodeActions: getActionsForJSDocTypes + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, }); - function getActionsForJSDocTypes(context) { - var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - // NOTE: Some locations are not handled yet: - // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments - var decl = ts.findAncestor(node, function (n) { - return n.kind === 203 /* AsExpression */ || - n.kind === 156 /* CallSignature */ || - n.kind === 157 /* ConstructSignature */ || - n.kind === 229 /* FunctionDeclaration */ || - n.kind === 154 /* GetAccessor */ || - n.kind === 158 /* IndexSignature */ || - n.kind === 173 /* MappedType */ || - n.kind === 152 /* MethodDeclaration */ || - n.kind === 151 /* MethodSignature */ || - n.kind === 147 /* Parameter */ || - n.kind === 150 /* PropertyDeclaration */ || - n.kind === 149 /* PropertySignature */ || - n.kind === 155 /* SetAccessor */ || - n.kind === 232 /* TypeAliasDeclaration */ || - n.kind === 185 /* TypeAssertionExpression */ || - n.kind === 227 /* VariableDeclaration */; - }); - if (!decl) - return; - var checker = context.program.getTypeChecker(); - var jsdocType = decl.type; - if (!jsdocType) - return; - var original = ts.getTextOfNode(jsdocType); - var type = checker.getTypeFromTypeNode(jsdocType); - var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; - if (jsdocType.kind === 274 /* JSDocNullableType */) { - // for nullable types, suggest the flow-compatible `T | null | undefined` - // in addition to the jsdoc/closure-compatible `T | null` - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); - actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); - } - return actions; - } - function createAction(declaration, fileName, original, replacement) { + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + break; + case 188 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), - changes: [{ - fileName: fileName, - textChanges: [{ - span: { start: declaration.getStart(), length: declaration.getWidth() }, - newText: replacement - }] - }], + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) }; } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -93021,7 +94150,10 @@ var ts; ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ], - getCodeActions: getImportCodeActions + getCodeActions: getImportCodeActions, + // TODO: GH#20315 + fixIds: [], + getAllCodeActions: ts.notImplemented, }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { @@ -93121,21 +94253,25 @@ var ts; return { description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), changes: changes, + // TODO: GH#20315 + fixId: undefined, kind: kind, moduleSpecifier: moduleSpecifier }; } function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var checker = context.program.getTypeChecker(); - var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + var program = context.program; + var checker = program.getTypeChecker(); + // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. + var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, + program: program, checker: checker, - compilerOptions: context.program.getCompilerOptions(), + compilerOptions: program.getCompilerOptions(), cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolToken.getText(), @@ -93172,7 +94308,10 @@ var ts; var declaration = declarations_13[_i]; var namespace = getNamespaceImportName(declaration); if (namespace) { - actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } } } @@ -93217,7 +94356,7 @@ var ts; } } function getCodeActionForNewImport(context, moduleSpecifier) { - var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var kind = context.kind, sourceFile = context.sourceFile, symbolName = context.symbolName; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); @@ -93230,10 +94369,10 @@ var ts; /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); var changes = ChangeTracker.with(context, function (changeTracker) { if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } else { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); + changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); } }); // if this file doesn't have any import statements, insert an import statement and then insert a new line @@ -93247,6 +94386,12 @@ var ts; literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); return literal; } + function usesJsExtensionOnImports(sourceFile) { + return ts.firstDefined(sourceFile.imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -93260,68 +94405,86 @@ var ts; ts.Debug.assertNever(kind); } } - function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + function getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; - var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); - if (!baseUrl) { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; + var addJsExtension = usesJsExtensionOnImports(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; } - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); }); // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) - return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + return ts.best(ts.arrayIterator(choicesForEachExportingModule), function (a, b) { return a[0].length < b[0].length; }); } codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } function getRelativePathNParents(relativePath) { var count = 0; for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { @@ -93335,10 +94498,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -93346,14 +94510,14 @@ var ts; 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); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -93368,12 +94532,12 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + return 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), options); + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); } }); } @@ -93481,15 +94645,25 @@ var ts; 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); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } - function removeExtensionAndIndexPostFix(fileName, options) { + function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); - return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + return addJsExtension + ? noExtension + ".js" + : ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -93509,7 +94683,7 @@ var ts; return [fromExistingImport]; } var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); - var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.program, ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); } function moduleSpecifierFromAnyImport(node) { @@ -93564,10 +94738,11 @@ var ts; * 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); + // Prefix the node instead of it replacing it, because this may be used for import completions and we don't want the text changes to overlap with the identifier being completed. + var changes = ChangeTracker.with(context, function (tracker) { + return tracker.changeIdentifierToPropertyAccess(sourceFile, namespacePrefix, symbolToken); + }); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes, "CodeChange", /*moduleSpecifier*/ undefined); } function getImportCodeActions(context) { var importFixContext = convertToImportCodeFixContext(context); @@ -93586,7 +94761,7 @@ var ts; } 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 */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */, /*excludeGlobals*/ false)); symbolName = symbol.name; } else { @@ -93625,11 +94800,12 @@ var ts; forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { // check if this symbol is already used var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); @@ -93641,6 +94817,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -93707,6 +94898,7 @@ var ts; // Need `|| "_"` to ensure result isn't empty. return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -93714,16 +94906,44 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); codefix.registerCodeFix({ - errorCodes: getApplicableDiagnosticCodes(), - getCodeActions: getDisableJsDiagnosticsCodeActions + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], + fixId: fixId, + }, + { + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [{ + span: { + start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, + length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 + }, + newText: "// @ts-nocheck" + newLineCharacter + }])], + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + fixId: undefined, + }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + if (err.start !== undefined) { + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); + } + }); }, }); - function getApplicableDiagnosticCodes() { - var allDiagnostcs = ts.Diagnostics; - return Object.keys(allDiagnostcs) - .filter(function (d) { return allDiagnostcs[d] && allDiagnostcs[d].category === ts.DiagnosticCategory.Error; }) - .map(function (d) { return allDiagnostcs[d].code; }); - } function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { var line = ts.getLineAndCharacterOfPosition(sourceFile, position).line; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); @@ -93748,32 +94968,6 @@ var ts; newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter }; } - function getDisableJsDiagnosticsCodeActions(context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { - return undefined; - } - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)] - }] - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { - start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, - length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 - }, - newText: "// @ts-nocheck" + newLineCharacter - }] - }] - }]; - } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -93781,64 +94975,33 @@ var ts; (function (ts) { var codefix; (function (codefix) { - function newNodesToChanges(newNodes, insertAfter, context) { - var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { - var newNode = newNodes_1[_i]; - changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); - } - var changes = changeTracker.getChanges(); - if (!ts.some(changes)) { - return changes; - } - ts.Debug.assert(changes.length === 1); - var consolidatedChanges = [{ - fileName: changes[0].fileName, - textChanges: [{ - span: changes[0].textChanges[0].span, - newText: changes[0].textChanges.reduce(function (prev, cur) { return prev + cur.newText; }, "") - }] - }]; - return consolidatedChanges; - } - codefix.newNodesToChanges = newNodesToChanges; /** * Finds members of the resolved type that are missing in the class pointed to by class decl * and generates source code for the missing members. * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, out) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); - var newNodes = []; - for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { - var symbol = missingMembers_1[_i]; - var newNode = createNewNodeForMemberSymbol(symbol, classDeclaration, checker); - if (newNode) { - if (Array.isArray(newNode)) { - newNodes = newNodes.concat(newNode); - } - else { - newNodes.push(newNode); - } + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); } } - return newNodes; } codefix.createMissingMemberNodes = createMissingMemberNodes; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function createNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -93849,10 +95012,10 @@ var ts; case 149 /* PropertySignature */: case 150 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); - var property = ts.createProperty( + out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, - /*initializer*/ undefined); - return property; + /*initializer*/ undefined)); + break; case 151 /* MethodSignature */: case 152 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff @@ -93864,70 +95027,65 @@ var ts; // correspondence of declarations and signatures. var signatures = checker.getSignaturesOfType(type, 0 /* Call */); if (!ts.some(signatures)) { - return undefined; + break; } if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody()); + break; } - var signatureDeclarations = []; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var signature = signatures_8[_i]; - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + outputMethod(signature, modifiers, name, createStubbedMethodBody()); } else { ts.Debug.assert(declarations.length === signatures.length); - var methodImplementingSignatures = createMethodImplementingSignatures(signatures, name, optional, modifiers); - signatureDeclarations.push(methodImplementingSignatures); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); } - return signatureDeclarations; - default: - return undefined; + break; } - function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); - if (signatureDeclaration) { - signatureDeclaration.decorators = undefined; - signatureDeclaration.modifiers = modifiers; - signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; - signatureDeclaration.body = body; - } - return signatureDeclaration; + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); } } - function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { - var parameters = createDummyParameters(callExpression.arguments.length, /*names*/ undefined, /*minArgumentCount*/ undefined, includeTypeScriptSyntax); - var typeParameters; - if (includeTypeScriptSyntax) { - var typeArgCount = ts.length(callExpression.typeArguments); - for (var i = 0; i < typeArgCount; i++) { - var name = typeArgCount < 8 ? String.fromCharCode(84 /* T */ + i) : "T" + i; - var typeParameter = ts.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined); - (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); - } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + if (!signatureDeclaration) { + return undefined; } - var newMethod = ts.createMethod( + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); + } + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + var typeArguments = _a.typeArguments, args = _a.arguments; + return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, /*asteriskToken*/ undefined, methodName, - /*questionToken*/ undefined, typeParameters, parameters, - /*type*/ includeTypeScriptSyntax ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, createStubbedMethodBody()); - return newMethod; + /*questionToken*/ undefined, + /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + }), + /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; - function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + function createDummyParameters(argCount, names, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { var newParameter = ts.createParameter( @@ -93936,7 +95094,7 @@ var ts; /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ addAnyType ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -93962,7 +95120,7 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -93981,7 +95139,6 @@ var ts; /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } - codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], @@ -94003,229 +95160,239 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ], - getCodeActions: getActionsForAddExplicitTypeAnnotation + errorCodes: errorCodes, + getCodeActions: function (_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + if (ts.isSourceFileJavaScript(sourceFile)) { + return undefined; // TODO: GH#20113 + } + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); + if (!fix) + return undefined; + var declaration = fix.declaration, textChanges = fix.textChanges; + var name = ts.getNameOfDeclaration(declaration); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); + return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var seenFunctions = ts.createMap(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + if (fix) + changes.push.apply(changes, fix.textChanges); + }); + }, }); - function getActionsForAddExplicitTypeAnnotation(_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var writer; - if (ts.isInJavaScriptFile(token)) { - return undefined; - } - switch (token.kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 131 /* ReadonlyKeyword */: - // Allowed - break; + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; default: - return undefined; + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!isAllowedTokenKind(token.kind)) { + return undefined; } - var containingFunction = ts.getContainingFunction(token); - var checker = program.getTypeChecker(); switch (errorCode) { // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - return getCodeActionForVariableDeclaration(token.parent); - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: - return getCodeActionForVariableUsage(token); + return getCodeActionForVariableDeclaration(token.parent, sourceFile, program, cancellationToken); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, sourceFile, program, cancellationToken); + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction); + return getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken); } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return getCodeActionForParameters(token.parent); + return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) + ? getCodeActionForParameters(token.parent, containingFunction, sourceFile, program, cancellationToken) + : undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; - } - return undefined; - function getCodeActionForVariableDeclaration(declaration) { - if (!ts.isIdentifier(declaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(declaration.name); - var typeString = type && typeToString(type, declaration); - if (!typeString) { - return undefined; - } - return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); - } - function getCodeActionForVariableUsage(token) { - var symbol = checker.getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 229 /* FunctionDeclaration */: - case 152 /* MethodDeclaration */: - case 153 /* Constructor */: - return true; - case 187 /* FunctionExpression */: - return !!declaration.name; - } - return false; + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; + default: + throw ts.Debug.fail(String(errorCode)); } - function getCodeActionForParameters(parameterDeclaration) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; - } - var types = inferTypeForParametersFromUsage(containingFunction) || - ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); - if (!types) { - return undefined; - } - var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (type && !parameter.type && !parameter.initializer) { - var typeString = typeToString(type, containingFunction); - return typeString ? { - span: { start: parameter.end, length: 0 }, - newText: ": " + typeString - } : undefined; - } - }).filter(function (c) { return !!c; }); - return textChanges.length ? [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: textChanges - }] - }] : undefined; - } - function getCodeActionForSetAccessor(setAccessorDeclaration) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || - inferTypeForVariableFromUsage(setAccessorParameter.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function isAllowedTokenKind(kind) { + switch (kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + return true; + default: + return false; } - function getCodeActionForGetAccessor(getAccessorDeclaration) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); - return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function getCodeActionForVariableDeclaration(declaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(declaration.name)) + return undefined; + var type = inferTypeForVariableFromUsage(declaration.name, sourceFile, program, cancellationToken); + return makeFix(declaration, declaration.name.getEnd(), type, program); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + return true; + case 187 /* FunctionExpression */: + return !!declaration.name; } - function createCodeActions(name, start, typeString) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: start, length: 0 }, - newText: typeString - }] - }] - }]; + return false; + } + function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; } - function getReferences(token) { - var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); - ts.Debug.assert(!!references, "Found no references!"); - ts.Debug.assert(references.length === 1, "Found more references than expected"); - return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, sourceFile, program, cancellationToken) : undefined; }); + if (!types) + return undefined; + // We didn't actually find a set of type inference positions matching each parameter position + if (containingFunction.parameters.length !== types.length) { + return undefined; } - function inferTypeForVariableFromUsage(token) { - return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { + var parameter = _a[0], type = _a[1]; + return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; + })); + return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration, sourceFile, program, cancellationToken) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; } - function inferTypeForParametersFromUsage(containingFunction) { - switch (containingFunction.kind) { - case 153 /* Constructor */: - case 187 /* FunctionExpression */: - case 229 /* FunctionDeclaration */: - case 152 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 153 /* Constructor */; - var searchToken = isConstructor ? - getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); - } - } - } - function getTypeAccessiblityWriter() { - if (!writer) { - var str_1 = ""; - var typeIsAccessible_1 = true; - var writeText = function (text) { return str_1 += text; }; - writer = { - string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { - typeIsAccessible_1 = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } - }; - } - writer.clear(); - return writer; + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, sourceFile, program, cancellationToken) || + inferTypeForVariableFromUsage(setAccessorParameter.name, sourceFile, program, cancellationToken); + return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); + } + function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; } - function typeToString(type, enclosingDeclaration) { - var writer = getTypeAccessiblityWriter(); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, sourceFile, program, cancellationToken); + var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20 /* CloseParenToken */, sourceFile); + return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + } + function makeFix(declaration, start, type, program) { + return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; + } + function makeChange(declaration, start, type, program) { + var typeString = type && typeToString(type, declaration, program.getTypeChecker()); + return typeString === undefined ? undefined : { span: ts.createTextSpan(start, 0), newText: ": " + typeString }; + } + function getReferences(token, sourceFile, program, cancellationToken) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), sourceFile, token.getStart(sourceFile)); + if (!references || references.length !== 1) { + return []; } - function getFirstChildOfKind(node, sourcefile, kind) { - for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { - var child = _a[_i]; - if (child.kind === kind) - return child; - } - return undefined; + return references[0].references.map(function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token, sourceFile, program, cancellationToken) { + return InferFromReference.inferTypeFromReferences(getReferences(token, sourceFile, program, cancellationToken), program.getTypeChecker(), cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + switch (containingFunction.kind) { + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 153 /* Constructor */; + var searchToken = isConstructor ? + ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, sourceFile, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); + } } } + function getTypeAccessiblityWriter(checker) { + var str = ""; + var typeIsAccessible = true; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return typeIsAccessible ? str : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + writeLine: function () { return writeText(" "); }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str = ""; typeIsAccessible = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } + }; + } + function typeToString(type, enclosingDeclaration, checker) { + var writer = getTypeAccessiblityWriter(checker); + checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); + return writer.getText(); + } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -94239,6 +95406,9 @@ var ts; } InferFromReference.inferTypeFromReferences = inferTypeFromReferences; function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (references.length === 0) { + return undefined; + } if (declaration.parameters) { var usageContext = {}; for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { @@ -94265,7 +95435,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; } } @@ -94477,12 +95647,12 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); @@ -94540,7 +95710,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); return isRestParameter ? checker.createArrayType(type) : type; } return undefined; @@ -94566,6 +95736,94 @@ var ts; })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + // This is the whole import statement, eg: + // import * as Bluebird from 'bluebird'; + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; + if (!ts.isImportDeclaration(node)) { + // No import quick fix for import calls + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + var replacement = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + var replacement_1 = ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 /* CallExpression */ : 183 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// /// /// @@ -94579,10 +95837,12 @@ var ts; /// /// /// +/// /// /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -94590,14 +95850,10 @@ var ts; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -94605,11 +95861,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -94819,15 +96075,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -94842,11 +96094,11 @@ var ts; if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -94861,7 +96113,6 @@ var ts; } var sourceFile = context.file; var ctorSymbol = getConstructorSymbol(context); - var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { @@ -94892,7 +96143,7 @@ var ts; return undefined; } // Because the preceding node could be touched, we need to insert nodes before delete nodes. - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { var deleteCallback = deletes_1[_i]; deleteCallback(); @@ -95057,6 +96308,488 @@ var ts; })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: actionName, + description: description, + actions: [ + { + description: description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182 /* CallExpression */: + return isAtTopLevelRequire(node); + case 180 /* PropertyAccessExpression */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228 /* VariableDeclarationList */: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227 /* VariableDeclaration */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228 /* VariableDeclarationList */) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 /* VariableStatement */ && varStatement.parent.kind === 269 /* SourceFile */; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249 /* ExternalModuleReference */: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + break; + } + case 182 /* CallExpression */: { + var call = parent; + if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 182 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + } + return false; + } + case 195 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 266 /* ShorthandPropertyAssignment */: + case 267 /* SpreadAssignment */: + return undefined; + case 265 /* PropertyAssignment */: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152 /* MethodDeclaration */: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84 /* ExportKeyword */)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 200 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 176 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + return parent.name !== node; + case 177 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -95065,14 +96798,9 @@ var ts; var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); /** * Compute the associated code actions * Exported for tests. @@ -95130,21 +96858,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); @@ -95163,7 +96891,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -95192,7 +96920,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -95253,6 +96981,14 @@ var ts; break; } } + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } if (ts.isReturnStatement(start) && !start.expression) { @@ -95479,7 +97215,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -95621,11 +97357,10 @@ var ts; case 153 /* Constructor */: return "constructor"; case 187 /* FunctionExpression */: - return scope.name - ? "function expression '" + scope.name.text + "'" - : "anonymous function expression"; case 229 /* FunctionDeclaration */: - return "function '" + scope.name.text + "'"; + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; case 188 /* ArrowFunction */: return "arrow function"; case 152 /* MethodDeclaration */: @@ -95682,7 +97417,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -95710,7 +97445,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -95736,13 +97471,10 @@ var ts; var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { - prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, - suffix: context.newLineCharacter - }); + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } var newNodes = []; // replace range with function call @@ -95781,7 +97513,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -95854,10 +97586,12 @@ var ts; newNodes.push(call); } } - var replacementRange = isReadonlyArray(range.range) - ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } - : { pos: range.range.getStart(), end: range.range.end }; - changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; @@ -95888,9 +97622,9 @@ var ts; var file = scope.getSourceFile(); var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); var isJS = ts.isInJavaScriptFile(scope); - var variableType = isJS + var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -95911,7 +97645,7 @@ var ts; // Declare var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } @@ -95924,8 +97658,8 @@ var ts; var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); if (oldVariableDeclaration) { // Declare - // CONSIDER: could detect that each is on a separate line - changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); @@ -95943,17 +97677,10 @@ var ts; // Declare var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); if (nodeToInsertBefore.pos === 0) { - // If we're at the beginning of the file, we need to take care not to insert before header comments - // (e.g. copyright, triple-slash references). Fortunately, this problem has already been solved - // for imports. - var insertionPos = ts.getSourceFileImportLocation(file); - changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { - prefix: insertionPos === 0 ? undefined : context.newLineCharacter, - suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter - }); + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); } else { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume if (node.parent.kind === 211 /* ExpressionStatement */) { @@ -96483,7 +98210,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); if (resolvedSymbol === symbol) { continue; } @@ -96623,15 +98350,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { // Then it will be available via `fixCannotFindModule`. @@ -96640,8 +98363,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -96696,13 +98419,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -96719,11 +98437,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -96781,6 +98499,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -97333,9 +99052,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = ts.getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; @@ -97620,8 +99339,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -97785,7 +99503,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -97795,10 +99513,11 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); }, @@ -97937,13 +99656,13 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -98296,13 +100015,19 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function getCombinedCodeFix(scope, fixId, formatOptions) { + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); @@ -98419,7 +100144,7 @@ var ts; return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { - // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // @@ -98489,7 +100214,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -98546,6 +100270,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -98593,19 +100318,6 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257 /* JsxAttribute */: - case 259 /* JsxSpreadAttribute */: - case 265 /* PropertyAssignment */: - case 266 /* ShorthandPropertyAssignment */: - case 152 /* MethodDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - return true; - } - return false; - } /** * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } */ @@ -98615,11 +100327,11 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: if (node.parent.kind === 145 /* ComputedPropertyName */) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } @@ -98637,20 +100349,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_9 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_7.push(symbol); } }); - return result_9; + return result_7; } if (symbol) { - result_9.push(symbol); - return result_9; + result_7.push(symbol); + return result_7; } } return undefined; @@ -98740,18 +100452,6 @@ var ts; Msg["Info"] = "Info"; Msg["Perf"] = "Perf"; })(Msg = server.Msg || (server.Msg = {})); - function getProjectRootPath(project) { - switch (project.projectKind) { - case server.ProjectKind.Configured: - return ts.getDirectoryPath(project.getProjectName()); - case server.ProjectKind.Inferred: - // TODO: fixme - return ""; - case server.ProjectKind.External: - var projectName = ts.normalizeSlashes(project.getProjectName()); - return ts.getDirectoryPath(projectName); - } - } function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), @@ -98759,7 +100459,7 @@ var ts; compilerOptions: project.getCompilationSettings(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, - projectRootPath: getProjectRootPath(project), + projectRootPath: project.getCurrentDirectory(), cachePath: cachePath, kind: "discover" }; @@ -99088,6 +100788,7 @@ var ts; CommandTypes["SignatureHelp"] = "signatureHelp"; /* @internal */ CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; + CommandTypes["Status"] = "status"; CommandTypes["TypeDefinition"] = "typeDefinition"; CommandTypes["ProjectInfo"] = "projectInfo"; CommandTypes["ReloadProjects"] = "reloadProjects"; @@ -99116,9 +100817,12 @@ var ts; CommandTypes["BreakpointStatement"] = "breakpointStatement"; CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; CommandTypes["GetCodeFixes"] = "getCodeFixes"; - CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; /* @internal */ CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; + CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix"; + /* @internal */ + CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; + CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand"; CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; @@ -99360,24 +101064,46 @@ var ts; }; } server.toEvent = toEvent; + function isProjectsArray(projects) { + return !!projects.length; + } + /** + * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. + */ + function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + var outputs = ts.flatMap(isProjectsArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!isProjectsArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (projects, path) { + var value = getValue(path); + outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); + }); + } + return comparer + ? ts.sortAndDeduplicate(outputs, comparer, areEqual) + : ts.deduplicate(outputs, areEqual); + } var Session = /** @class */ (function () { function Session(opts) { var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, + _a[server.CommandNames.Status] = function () { + var response = { version: ts.version }; + return _this.requiredResponse(response); + }, _a[server.CommandNames.OpenExternalProject] = function (request) { _this.projectService.openExternalProject(request.arguments, /*suppressRefreshOfInferredProjects*/ false); - // TODO: report errors + // TODO: GH#20447 report errors return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.OpenExternalProjects] = function (request) { _this.projectService.openExternalProjects(request.arguments.projects); - // TODO: report errors + // TODO: GH#20447 report errors return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.CloseExternalProject] = function (request) { _this.projectService.closeExternalProject(request.arguments.projectFileName); - // TODO: report errors + // TODO: GH#20447 report errors return _this.requiredResponse(/*response*/ true); }, _a[server.CommandNames.SynchronizeProjectList] = function (request) { @@ -99614,9 +101340,14 @@ var ts; _a[server.CommandNames.GetCodeFixesFull] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false)); }, + _a[server.CommandNames.GetCombinedCodeFix] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ true)); + }, + _a[server.CommandNames.GetCombinedCodeFixFull] = function (request) { + return _this.requiredResponse(_this.getCombinedCodeFix(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. + return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments)); }, _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); @@ -100062,6 +101793,7 @@ var ts; }; Session.prototype.getProjects = function (args) { var projects; + var symLinkedProjects; if (args.projectFileName) { var project = this.getProject(args.projectFileName); if (project) { @@ -100071,13 +101803,14 @@ var ts; else { var scriptInfo = this.projectService.getScriptInfo(args.file); projects = scriptInfo.containingProjects; + symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } // filter handles case when 'projects' is undefined projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); - if (!projects || !projects.length) { + if ((!projects || !projects.length) && !symLinkedProjects) { return server.Errors.ThrowNoProject(); } - return projects; + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; }; Session.prototype.getDefaultProject = function (args) { if (args.projectFileName) { @@ -100090,6 +101823,7 @@ var ts; return info.getDefaultProject(); }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); @@ -100106,7 +101840,7 @@ var ts; locs: server.emptyArray }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); if (!renameLocations) { return server.emptyArray; @@ -100139,7 +101873,7 @@ var ts; return { info: renameInfo, locs: locs }; } else { - return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (p, file) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, /*comparer*/ undefined, renameLocationIsEqualTo); } function renameLocationIsEqualTo(a, b) { @@ -100175,6 +101909,7 @@ var ts; } }; Session.prototype.getReferences = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); @@ -100189,7 +101924,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { return server.emptyArray; @@ -100217,7 +101952,7 @@ var ts; }; } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { return project.getLanguageService().findReferences(file, position); }, /*comparer*/ undefined, ts.equateValues); } function areReferencesResponseItemsForTheSameLocation(a, b) { @@ -100417,10 +102152,10 @@ var ts; if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); } @@ -100439,28 +102174,29 @@ var ts; return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source); }); return simplifiedResult - ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action, scriptInfo); }) })); }) + ? result.map(function (details) { return (__assign({}, details, { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(project, action); }) })); }) : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var _this = this; var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); if (!info) { return server.emptyArray; } - var result = []; // if specified a project, we only return affected file list in this project - var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { - var project = projectsToSearch_1[_i]; + var projects = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + var symLinkedProjects = !args.projectFileName && this.projectService.getSymlinkedProjects(info); + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects, function (project, info) { + var result; if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.getCompilationSettings().noEmit) { - result.push({ + result = { projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out - }); + }; } - } - return result; + return result; + }); }; Session.prototype.emitFile = function (args) { var _this = this; @@ -100600,7 +102336,10 @@ var ts; var projects = this.getProjects(args); var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; if (simplifiedResult) { - return server.combineProjectOutput(projects, function (project) { + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); if (!navItems) { return server.emptyArray; @@ -100632,7 +102371,12 @@ var ts; /*comparer*/ undefined, areNavToItemsForTheSameLocation); } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); }, + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } + return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); + }, /*comparer*/ undefined, navigateToItemIsEqualTo); } function navigateToItemIsEqualTo(a, b) { @@ -100690,7 +102434,6 @@ var ts; return project.getLanguageService().getApplicableRefactors(file, position || textRange); }; Session.prototype.getEditsForRefactor = function (args, simplifiedResult) { - var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; @@ -100705,15 +102448,9 @@ var ts; var mappedRenameLocation = void 0; if (renameFilename !== undefined && renameLocation !== undefined) { var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); - var snapshot = renameScriptInfo.getSnapshot(); - var oldText = snapshot.getText(0, snapshot.getLength()); - mappedRenameLocation = getLocationInNewDocument(oldText, renameFilename, renameLocation, edits); + mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } - return { - renameLocation: mappedRenameLocation, - renameFilename: renameFilename, - edits: edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) - }; + return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(project, edits) }; } else { return result; @@ -100733,25 +102470,33 @@ var ts; return undefined; } if (simplifiedResult) { - return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + return codeActions.map(function (codeAction) { return _this.mapCodeAction(project, codeAction); }); } else { return codeActions; } }; - Session.prototype.applyCodeActionCommand = function (commandName, requestSeq, args) { - var _this = this; + Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { + var scope = _a.scope, fixId = _a.fixId; + ts.Debug.assert(scope.type === "file"); + var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; + var formatOptions = this.projectService.getFormatCodeOptions(file); + var res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId, formatOptions); + if (simplifiedResult) { + return { changes: this.mapTextChangesToCodeEdits(project, res.changes), commands: res.commands }; + } + else { + return res; + } + }; + Session.prototype.applyCodeActionCommand = function (args) { var commands = args.command; // They should be sending back the command we sent them. - var _loop_11 = function (command) { - var project = this_1.getFileAndProject(command).project; - var output = function (success, message) { return _this.doOutput({}, commandName, requestSeq, success, message); }; - project.getLanguageService().applyCodeActionCommand(command).then(function (result) { output(/*success*/ true, result.successMessage); }, function (error) { output(/*success*/ false, error); }); - }; - var this_1 = this; for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - _loop_11(command); + var project = this.getFileAndProject(command).project; + project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); } + return {}; }; Session.prototype.getStartAndEndPosition = function (args, scriptInfo) { var startPosition = undefined, endPosition = undefined; @@ -100772,18 +102517,18 @@ var ts; } return { startPosition: startPosition, endPosition: endPosition }; }; - Session.prototype.mapCodeAction = function (_a, scriptInfo) { + Session.prototype.mapCodeAction = function (project, _a) { var _this = this; - 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 }; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId; + var changes = unmappedChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); + return { description: description, changes: changes, commands: commands, fixId: fixId }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; - var scriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(textChanges.fileName)); + return textChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); + }; + Session.prototype.mapTextChangesToCodeEditsUsingScriptinfo = function (textChanges, scriptInfo) { + var _this = this; return { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) @@ -100956,8 +102701,8 @@ var ts; continue; } for (var i = textChanges_3.length - 1; i >= 0; i--) { - var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_8 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_8); + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; @@ -101296,7 +103041,7 @@ var ts; return this.index.getText(rangeStart, rangeEnd - rangeStart); }; LineIndexSnapshot.prototype.getLength = function () { - return this.index.root.charCount(); + return this.index.getLength(); }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { @@ -101872,7 +103617,7 @@ var ts; server.TextStorage = TextStorage; /*@internal*/ function isDynamicFileName(fileName) { - return ts.getBaseFileName(fileName)[0] === "^"; + return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^"; } server.isDynamicFileName = isDynamicFileName; var ScriptInfo = /** @class */ (function () { @@ -101890,6 +103635,7 @@ var ts; this.textStorage = new TextStorage(host, fileName); if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); + this.realpath = this.path; } this.scriptKind = scriptKind ? scriptKind @@ -101925,6 +103671,28 @@ var ts; ScriptInfo.prototype.getSnapshot = function () { return this.textStorage.getSnapshot(); }; + ScriptInfo.prototype.ensureRealPath = function () { + if (this.realpath === undefined) { + // Default is just the path + this.realpath = this.path; + if (this.host.realpath) { + ts.Debug.assert(!!this.containingProjects.length); + var project = this.containingProjects[0]; + var realpath = this.host.realpath(this.path); + if (realpath) { + this.realpath = project.toPath(realpath); + // If it is different from this.path, add to the map + if (this.realpath !== this.path) { + project.projectService.realpathToScriptInfos.add(this.realpath, this); + } + } + } + } + }; + /*@internal*/ + ScriptInfo.prototype.getRealpathIfDifferent = function () { + return this.realpath && this.realpath !== this.path ? this.realpath : undefined; + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatCodeSettings; }; @@ -101932,6 +103700,9 @@ var ts; var isNew = !this.isAttached(project); if (isNew) { this.containingProjects.push(project); + if (!project.getCompilerOptions().preserveSymlinks) { + this.ensureRealPath(); + } } return isNew; }; @@ -101971,7 +103742,7 @@ var ts; for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; if (p.projectKind === server.ProjectKind.Configured) { - p.directoryStructureHost.addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); } var isInfoRoot = p.isRoot(this); // detach is unnecessary since we'll clean the list of containing projects anyways @@ -102025,8 +103796,7 @@ var ts; return this.textStorage.getVersion(); }; ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.textStorage.getSnapshot(); - this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot())); }; /*@internal*/ ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { @@ -102090,6 +103860,181 @@ var ts; /* @internal */ var ts; (function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; var ConfigFileProgramReloadLevel; (function (ConfigFileProgramReloadLevel) { ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; @@ -102146,6 +104091,13 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -102227,7 +104179,7 @@ var ts; var ts; (function (ts) { ts.maxNumberOfFilesToIterateForInvalidation = 256; - function createResolutionCache(resolutionHost, rootDirForResolution) { + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; @@ -102239,6 +104191,7 @@ var ts; var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -102299,8 +104252,8 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } - function createHasInvalidatedResolution() { - if (allFilesHaveInvalidatedResolution) { + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { // Any file asked would have invalidated resolution filesWithInvalidatedResolutions = undefined; return ts.returnTrue; @@ -102421,8 +104374,8 @@ var ts; return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, /*reusedNames*/ undefined, /*logChanges*/ false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); @@ -102561,9 +104514,9 @@ var ts; function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { + if (cachedDirectoryStructureHost) { // Since the file existance changed, update the sourceFiles cache - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // If the files are added to project root or node_modules directory, always run through the invalidation process // Otherwise run through invalidation only if adding to the immediate directory @@ -102654,6 +104607,10 @@ var ts; if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { return false; } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } @@ -102672,9 +104629,9 @@ var ts; // Create new watch and recursive info return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { + if (cachedDirectoryStructureHost) { // Since the file existance changed, update the sourceFiles cache - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // For now just recompile // We could potentially store more data here about whether it was/would be really be used or not @@ -102841,12 +104798,319 @@ var ts; server.TypingsCache = TypingsCache; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + 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 (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.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 (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // 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(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); /// /// /// /// /// -/// +/// var ts; (function (ts) { var server; @@ -102935,17 +105199,16 @@ var ts; var Project = /** @class */ (function () { /*@internal*/ function Project( - /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, - /*@internal*/ directoryStructureHost, currentDirectory) { + /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; this.documentRegistry = documentRegistry; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; - this.directoryStructureHost = directoryStructureHost; this.rootFiles = []; this.rootFilesMap = ts.createMap(); + this.plugins = []; this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); this.languageServiceEnabled = true; /** @@ -102966,6 +105229,7 @@ var ts; this.projectStateVersion = 0; /*@internal*/ this.hasChangedAutomaticTypeDirectiveNames = false; + this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { @@ -102986,7 +105250,7 @@ var ts; this.realpath = function (path) { return host.realpath(path); }; } // Use the current directory as resolution root only if the project created using current directory string - this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true); this.languageService = ts.createLanguageService(this, this.documentRegistry); if (!languageServiceEnabled) { this.disableLanguageService(); @@ -103037,7 +105301,7 @@ var ts; return this.getCompilationSettings(); }; Project.prototype.getNewLine = function () { - return this.directoryStructureHost.newLine; + return this.projectService.host.newLine; }; Project.prototype.getProjectVersion = function () { return this.projectStateVersion.toString(); @@ -103094,13 +105358,13 @@ var ts; return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); }; Project.prototype.useCaseSensitiveFileNames = function () { - return this.directoryStructureHost.useCaseSensitiveFileNames; + return this.projectService.host.useCaseSensitiveFileNames; }; Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }; Project.prototype.readFile = function (fileName) { - return this.directoryStructureHost.readFile(fileName); + return this.projectService.host.readFile(fileName); }; Project.prototype.fileExists = function (file) { // As an optimization, don't hit the disks for files we already know don't exist @@ -103109,7 +105373,7 @@ var ts; return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); }; Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, /*logChanges*/ true); + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }; Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); @@ -103121,6 +105385,10 @@ var ts; return this.directoryStructureHost.getDirectories(path); }; /*@internal*/ + Project.prototype.getCachedDirectoryStructureHost = function () { + return undefined; + }; + /*@internal*/ Project.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); }; @@ -103170,15 +105438,6 @@ var ts; } return this.languageService; }; - Project.prototype.ensureBuilder = function () { - var _this = this; - if (!this.builder) { - this.builder = ts.createBuilder({ - getCanonicalFileName: this.projectService.toCanonicalFileName, - computeHash: function (data) { return _this.projectService.host.createHash(data); } - }); - } - }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -103188,8 +105447,8 @@ var ts; return []; } this.updateGraph(); - this.ensureBuilder(); - return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** * Returns true if emit was conducted @@ -103221,14 +105480,35 @@ var ts; } this.languageService.cleanupSemanticCache(); this.languageServiceEnabled = false; + this.builderState = undefined; this.resolutionCache.closeTypeRootsWatch(); this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false); }; Project.prototype.getProjectName = function () { return this.projectName; }; + Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) { + if (!newTypeAcquisition || !newTypeAcquisition.include) { + // Nothing to filter out, so just return as-is + return newTypeAcquisition; + } + return __assign({}, newTypeAcquisition, { include: this.removeExistingTypings(newTypeAcquisition.include) }); + }; Project.prototype.getExternalFiles = function () { - return server.emptyArray; + var _this = this; + return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.getExternalFiles !== "function") + return; + try { + return plugin.getExternalFiles(_this); + } + catch (e) { + _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + if (e.stack) { + _this.projectService.logger.info(e.stack); + } + } + })); }; Project.prototype.getSourceFile = function (path) { if (!this.program) { @@ -103258,7 +105538,7 @@ var ts; this.rootFilesMap = undefined; this.externalFiles = undefined; this.program = undefined; - this.builder = undefined; + this.builderState = undefined; this.resolutionCache.clear(); this.resolutionCache = undefined; this.cachedUnresolvedImportsPerFile = undefined; @@ -103418,7 +105698,8 @@ var ts; Project.prototype.markAsDirty = function () { this.projectStateVersion++; }; - Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, result) { + /* @internal */ + Project.prototype.extractUnresolvedImportsFromSourceFile = function (file, result, ambientModules) { var cached = this.cachedUnresolvedImportsPerFile.get(file.path); if (cached) { // found cached result - use it and return @@ -103432,7 +105713,7 @@ var ts; if (file.resolvedModules) { file.resolvedModules.forEach(function (resolvedModule, name) { // pick unresolved non-relative names - if (!resolvedModule && !ts.isExternalModuleNameRelative(name)) { + if (!resolvedModule && !ts.isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { // for non-scoped names extract part up-to the first slash // for scoped names - extract up to the second slash var trimmed = name.trim(); @@ -103449,6 +105730,9 @@ var ts; }); } this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); + function isAmbientlyDeclaredModule(name) { + return ambientModules.some(function (m) { return m === name; }); + } }; /** * Updates set of files that contribute to this project @@ -103474,9 +105758,10 @@ var ts; // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch if (hasChanges || changedFiles.length) { var result = []; + var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); }); for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { var sourceFile = _b[_a]; - this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + this.extractUnresolvedImportsFromSourceFile(sourceFile, result, ambientModules); } this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); } @@ -103484,21 +105769,23 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } - if (this.builder) { - this.builder.updateProgram(this.program); - } } else { this.lastCachedUnresolvedImportsList = undefined; - if (this.builder) { - this.builder.clear(); - } } if (hasChanges) { this.projectStructureVersion++; } return !hasChanges; }; + /* @internal */ + Project.prototype.getCurrentProgram = function () { + return this.program; + }; + Project.prototype.removeExistingTypings = function (include) { + var existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + return include.filter(function (i) { return existing.indexOf(i) < 0; }); + }; Project.prototype.setTypings = function (typings) { if (ts.arrayIsEqualTo(this.typingFiles, typings)) { return false; @@ -103567,7 +105854,7 @@ var ts; var _this = this; var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { if (_this.projectKind === ProjectKind.Configured) { - _this.directoryStructureHost.addOrDeleteFile(fileName, missingFilePath, eventKind); + _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); } if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { _this.missingFilesMap.delete(missingFilePath); @@ -103676,6 +105963,82 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; + Project.prototype.enableGlobalPlugins = function () { + var host = this.projectService.host; + var options = this.getCompilationSettings(); + if (!host.require) { + this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); + return; + } + // Search our peer node_modules, then any globally-specified probe paths + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); + if (this.projectService.globalPlugins) { + var _loop_11 = function (globalPluginName) { + // Skip empty names from odd commandline parses + if (!globalPluginName) + return "continue"; + // Skip already-locally-loaded plugins + if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) + return "continue"; + // Provide global: true so plugins can detect why they can't find their config + this_1.projectService.logger.info("Loading global plugin " + globalPluginName); + this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + }; + var this_1 = this; + // Enable global plugins with synthetic configuration entries + for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { + var globalPluginName = _a[_i]; + _loop_11(globalPluginName); + } + } + }; + Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { + var _this = this; + this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + var log = function (message) { + _this.projectService.logger.info(message); + }; + for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) { + var searchPath = searchPaths_1[_i]; + var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); + if (resolvedModule) { + this.enableProxy(resolvedModule, pluginConfigEntry); + return; + } + } + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); + }; + Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) { + try { + if (typeof pluginModuleFactory !== "function") { + this.projectService.logger.info("Skipped loading plugin " + configEntry.name + " because it did expose a proper factory function"); + return; + } + var info = { + config: configEntry, + project: this, + languageService: this.languageService, + languageServiceHost: this, + serverHost: this.projectService.host + }; + var pluginModule = pluginModuleFactory({ typescript: ts }); + var newLS = pluginModule.create(info); + for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { + var k = _a[_i]; + if (!(k in newLS)) { + this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); + newLS[k] = this.languageService[k]; + } + } + this.projectService.logger.info("Plugin validation succeded"); + this.languageService = newLS; + this.plugins.push(pluginModule); + } + catch (e) { + this.projectService.logger.info("Plugin activation failed: " + e); + } + }; return Project; }()); server.Project = Project; @@ -103693,6 +106056,7 @@ var ts; /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this; _this._isJsInferredProject = false; _this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); + _this.enableGlobalPlugins(); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -103774,7 +106138,6 @@ var ts; function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, cachedDirectoryStructureHost) { var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.plugins = []; /** Ref count to the project when opened from external project */ _this.externalProjectRefCount = 0; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); @@ -103827,71 +106190,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - if (this.projectService.globalPlugins) { - var _loop_12 = function (globalPluginName) { - // Skip empty names from odd commandline parses - if (!globalPluginName) - return "continue"; - // Skip already-locally-loaded plugins - if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) - return "continue"; - // Provide global: true so plugins can detect why they can't find their config - this_2.projectService.logger.info("Loading global plugin " + globalPluginName); - this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); - }; - var this_2 = this; - // Enable global plugins with synthetic configuration entries - for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { - var globalPluginName = _c[_b]; - _loop_12(globalPluginName); - } - } - }; - ConfiguredProject.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { - var _this = this; - this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); - var log = function (message) { - _this.projectService.logger.info(message); - }; - for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) { - var searchPath = searchPaths_1[_i]; - var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log); - if (resolvedModule) { - this.enableProxy(resolvedModule, pluginConfigEntry); - return; - } - } - this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); - }; - ConfiguredProject.prototype.enableProxy = function (pluginModuleFactory, configEntry) { - try { - if (typeof pluginModuleFactory !== "function") { - this.projectService.logger.info("Skipped loading plugin " + configEntry.name + " because it did expose a proper factory function"); - return; - } - var info = { - config: configEntry, - project: this, - languageService: this.languageService, - languageServiceHost: this, - serverHost: this.projectService.host - }; - var pluginModule = pluginModuleFactory({ typescript: ts }); - var newLS = pluginModule.create(info); - for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { - var k = _a[_i]; - if (!(k in newLS)) { - this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); - newLS[k] = this.languageService[k]; - } - } - this.projectService.logger.info("Plugin validation succeded"); - this.languageService = newLS; - this.plugins.push(pluginModule); - } - catch (e) { - this.projectService.logger.info("Plugin activation failed: " + e); - } + this.enableGlobalPlugins(); }; /** * Get the errors that dont have any file name associated @@ -103909,27 +106208,11 @@ var ts; this.projectErrors = projectErrors; }; ConfiguredProject.prototype.setTypeAcquisition = function (newTypeAcquisition) { - this.typeAcquisition = newTypeAcquisition; + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); }; ConfiguredProject.prototype.getTypeAcquisition = function () { return this.typeAcquisition; }; - ConfiguredProject.prototype.getExternalFiles = function () { - var _this = this; - return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { - if (typeof plugin.getExternalFiles !== "function") - return; - try { - return plugin.getExternalFiles(_this); - } - catch (e) { - _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); - if (e.stack) { - _this.projectService.logger.info(e.stack); - } - } - })); - }; /*@internal*/ ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { var _this = this; @@ -104026,7 +106309,7 @@ var ts; ts.Debug.assert(!!newTypeAcquisition.include, "newTypeAcquisition.include may not be null/undefined"); ts.Debug.assert(!!newTypeAcquisition.exclude, "newTypeAcquisition.exclude may not be null/undefined"); ts.Debug.assert(typeof newTypeAcquisition.enable === "boolean", "newTypeAcquisition.enable may not be null/undefined"); - this.typeAcquisition = newTypeAcquisition; + this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); }; return ExternalProject; }(Project)); @@ -104155,16 +106438,6 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; - /** - * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. - */ - function combineProjectOutput(projects, action, comparer, areEqual) { - var outputs = ts.flatMap(projects, action); - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); - } - server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -104281,6 +106554,9 @@ var ts; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + if (this.host.realpath) { + this.realpathToScriptInfos = ts.createMultiMap(); + } this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); @@ -104387,9 +106663,11 @@ var ts; } switch (response.kind) { case server.ActionSet: + project.resolutionCache.clear(); this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings); break; case server.ActionInvalidate: + project.resolutionCache.clear(); this.typingsCache.deleteTypingsForProject(response.projectName); break; } @@ -104552,15 +106830,6 @@ var ts; this.refreshInferredProjects(); } }; - ProjectService.prototype.findContainingExternalProject = function (fileName) { - for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.containsFile(fileName)) { - return proj; - } - } - return undefined; - }; ProjectService.prototype.getFormatCodeOptions = function (file) { var formatCodeSettings; if (file) { @@ -104592,7 +106861,7 @@ var ts; if (info.containingProjects.length === 0) { // Orphan script info, remove it as we can always reload it on next open file request this.stopWatchingScriptInfo(info); - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); } else { // file has been changed which might affect the set of referenced files in projects that include @@ -104606,7 +106875,7 @@ var ts; this.stopWatchingScriptInfo(info); // TODO: handle isOpen = true case if (!info.isScriptOpen()) { - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); // capture list of projects since detachAllProjects will wipe out original list var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); @@ -104709,7 +106978,7 @@ var ts; ts.Debug.assert(info.isOrphan()); var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || - this.createInferredProject(ts.getDirectoryPath(info.path)); + this.createInferredProject(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path)); project.addRoot(info); project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { @@ -104811,10 +107080,17 @@ var ts; if (!info.isScriptOpen() && info.isOrphan()) { // if there are not projects that include this script info - delete it _this.stopWatchingScriptInfo(info); - _this.filenameToScriptInfo.delete(info.path); + _this.deleteScriptInfo(info); } }); }; + ProjectService.prototype.deleteScriptInfo = function (info) { + this.filenameToScriptInfo.delete(info.path); + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + this.realpathToScriptInfos.remove(realpath, info); + } + }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { @@ -105219,7 +107495,7 @@ var ts; }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); var languageServiceEnabled = !this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); @@ -105351,7 +107627,7 @@ var ts; }); }; ProjectService.prototype.getOrCreateInferredProjectForProjectRootPathIfEnabled = function (info, projectRootPath) { - if (!this.useInferredProjectPerProjectRoot) { + if (info.isDynamic || !this.useInferredProjectPerProjectRoot) { return undefined; } if (projectRootPath) { @@ -105421,6 +107697,44 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; + /** + * Returns the projects that contain script info through SymLink + * Note that this does not return projects in info.containingProjects + */ + /*@internal*/ + ProjectService.prototype.getSymlinkedProjects = function (info) { + var projects; + if (this.realpathToScriptInfos) { + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + ts.forEach(this.realpathToScriptInfos.get(realpath), combineProjects); + } + ts.forEach(this.realpathToScriptInfos.get(info.path), combineProjects); + } + return projects; + function combineProjects(toAddInfo) { + if (toAddInfo !== info) { + var _loop_12 = function (project) { + // Add the projects only if they can use symLink targets and not already in the list + if (project.languageServiceEnabled && + !project.getCompilerOptions().preserveSymlinks && + !ts.contains(info.containingProjects, project)) { + if (!projects) { + projects = ts.createMultiMap(); + projects.add(toAddInfo.path, project); + } + else if (!ts.forEachEntry(projects, function (projs, path) { return path === toAddInfo.path ? false : ts.contains(projs, project); })) { + projects.add(toAddInfo.path, project); + } + } + }; + for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + _loop_12(project); + } + } + } + }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.fileWatcher); @@ -105448,13 +107762,15 @@ var ts; return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); }; ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + var _this = this; ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); var info = this.getScriptInfoForPath(path); if (!info) { - ts.Debug.assert(ts.isRootedDiskPath(fileName) || openedByClient, "Script info with relative file name can only be open script info"); - ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); var isDynamic = server.isDynamicFileName(fileName); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info"; }); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); // If the file is not opened by client and the file doesnot exist on the disk, return if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; @@ -105653,13 +107969,24 @@ var ts; ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; + ProjectService.prototype.findExternalProjetContainingOpenScriptInfo = function (info) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + // Ensure project structure is uptodate to check if info is present in external project + proj.updateGraph(); + if (proj.containsScriptInfo(info)) { + return proj; + } + } + return undefined; + }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { var _this = this; var configFileName; var sendConfigFileDiagEvent = false; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); - var project = this.findContainingExternalProject(fileName); + var project = this.findExternalProjetContainingOpenScriptInfo(info); if (!project) { configFileName = this.getConfigFileNameForFile(info, projectRootPath); if (configFileName) { @@ -105669,6 +107996,10 @@ var ts; // Send the event only if the project got created as part of this open request sendConfigFileDiagEvent = true; } + else { + // Ensure project is ready to check if it contains opened script info + project.updateGraph(); + } } } if (project && !project.languageServiceEnabled) { @@ -105858,11 +108189,11 @@ var ts; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; var _loop_14 = function (name) { - var rule = this_3.safelist[name]; + var rule = this_2.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; if (rule.match.test(root)) { - this_3.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); + this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'"); // If the file matches, collect its types packages and exclude rules if (rule.types) { for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { @@ -105915,7 +108246,7 @@ var ts; } } }; - var this_3 = this; + var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; _loop_14(name); @@ -105933,13 +108264,13 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_4.legacySafelist[cleanedTypingName]) { - this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); + if (this_3.legacySafelist[cleanedTypingName]) { + this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); // *exclude* it from the project... exclude = true; // ... but *include* it in the list of types to acquire - var typeName = this_4.legacySafelist[cleanedTypingName]; + var typeName = this_3.legacySafelist[cleanedTypingName]; // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); @@ -105958,7 +108289,7 @@ var ts; } } }; - var this_4 = this; + var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { _loop_16(i); } @@ -106572,10 +108903,10 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = JSON.parse(options); + var localOptions = options === undefined ? undefined : JSON.parse(options); return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); }); }; @@ -106711,7 +109042,7 @@ var ts; var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { // for now treat files as JavaScript - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -106746,8 +109077,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 9573a51760fd3..3cbca96f8fa97 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -453,6 +454,9 @@ declare namespace ts { interface JSDocContainer { } type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -604,15 +608,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends NamedDeclaration { - propertyName?: PropertyName; - dotDotDotToken?: DotDotDotToken; - name: DeclarationName; - questionToken?: QuestionToken; - exclamationToken?: ExclamationToken; - type?: TypeNode; - initializer?: Expression; - } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -643,7 +639,7 @@ declare namespace ts { body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -660,30 +656,30 @@ declare namespace ts { } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; + parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -881,7 +877,7 @@ declare namespace ts { type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; - type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; @@ -905,6 +901,7 @@ declare namespace ts { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; + name: never; } interface LiteralLikeNode extends Node { text: string; @@ -1279,7 +1276,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassDeclaration | ClassExpression; + parent?: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1366,6 +1363,7 @@ declare namespace ts { interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; parent?: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier?: Expression; @@ -1620,7 +1618,7 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. @@ -1731,6 +1729,16 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -1750,7 +1758,8 @@ declare namespace ts { getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; /** * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead * This will be removed in a future version. @@ -1790,33 +1799,79 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, SuppressAnyReturnType = 256, WriteTypeParametersInQualifiedName = 512, - AllowThisInObjectLiteral = 1024, - AllowQualifedNameInPlaceOfIdentifier = 2048, - AllowAnonymousIdentifier = 8192, - AllowEmptyUnionOrIntersection = 16384, - AllowEmptyTuple = 32768, - IgnoreErrors = 60416, - InObjectTypeLiteral = 1048576, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + IgnoreErrors = 3112960, + InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, + InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469295, + } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + } + /** + * @deprecated + */ interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; - buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - interface SymbolWriter { + /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; + /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + } + /** + * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString + */ + interface SymbolWriter extends SymbolTracker { writeKeyword(text: string): void; writeOperator(text: string): void; writePunctuation(text: string): void; @@ -1829,34 +1884,6 @@ declare namespace ts { increaseIndent(): void; decreaseIndent(): void; clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError(): void; - reportPrivateInBaseOfClassExpression(propertyName: string): void; - reportInaccessibleUniqueSymbolError(): void; - } - enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 4, - NoTruncation = 8, - WriteArrowStyleSignature = 16, - WriteOwnNameForAnyLike = 32, - WriteTypeArgumentsOfSignature = 64, - InElementType = 128, - UseFullyQualifiedType = 256, - InFirstTypeArgument = 512, - InTypeAlias = 1024, - SuppressAnyReturnType = 4096, - AddUndefined = 8192, - WriteClassExpressionAsTypeLiteral = 16384, - InArrayType = 32768, - UseAliasDefinedOutsideCurrentScope = 65536, - AllowUniqueESSymbolType = 131072, - } - enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, } enum TypePredicateKind { This = 0, @@ -2071,6 +2098,7 @@ declare namespace ts { EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, ContainsSpread = 1024, + ReverseMapped = 2048, ClassOrInterface = 3, } interface ObjectType extends Type { @@ -2150,15 +2178,14 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - Contravariant = 1, - NakedTypeVariable = 2, - MappedType = 4, - ReturnType = 8, - NeverType = 16, + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, } interface InferenceInfo { typeParameter: TypeParameter; candidates: Type[]; + contraCandidates: Type[]; inferredType: Type; priority: InferencePriority; topLevel: boolean; @@ -2299,6 +2326,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -2472,12 +2500,13 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; + createHash?(data: string): string; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2634,6 +2663,10 @@ declare namespace ts { * collisions. */ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -2689,6 +2722,13 @@ declare namespace ts { interface PrinterOptions { removeComments?: boolean; newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + } + interface SymbolTracker { + trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + reportInaccessibleThisError?(): void; + reportPrivateInBaseOfClassExpression?(propertyName: string): void; + reportInaccessibleUniqueSymbolError?(): void; } interface TextSpan { start: number; @@ -2701,6 +2741,71 @@ declare namespace ts { interface SyntaxList extends Node { _children: Node[]; } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + DelimitersMask = 28, + AllowTrailingComma = 32, + Indented = 64, + SpaceBetweenBraces = 128, + SpaceBetweenSiblings = 256, + Braces = 512, + Parenthesis = 1024, + AngleBrackets = 2048, + SquareBrackets = 4096, + BracketsMask = 7680, + OptionalIfUndefined = 8192, + OptionalIfEmpty = 16384, + Optional = 24576, + PreferNewLine = 32768, + NoTrailingNewLine = 65536, + NoInterveningComments = 131072, + NoSpaceIfEmpty = 262144, + SingleElement = 524288, + Modifiers = 131328, + HeritageClauses = 256, + SingleLineTypeLiteralMembers = 448, + MultiLineTypeLiteralMembers = 65, + TupleTypeElements = 336, + UnionTypeConstituents = 260, + IntersectionTypeConstituents = 264, + ObjectBindingPatternElements = 262576, + ArrayBindingPatternElements = 262448, + ObjectLiteralExpressionProperties = 263122, + ArrayLiteralExpressionElements = 4466, + CommaListElements = 272, + CallExpressionArguments = 1296, + NewExpressionArguments = 9488, + TemplateExpressionSpans = 131072, + SingleLineBlockStatements = 384, + MultiLineBlockStatements = 65, + VariableDeclarationList = 272, + SingleLineFunctionBodyStatements = 384, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 256, + ClassMembers = 65, + InterfaceMembers = 65, + EnumMembers = 81, + CaseBlockClauses = 65, + NamedImportsOrExportsElements = 432, + JsxElementOrFragmentChildren = 131072, + JsxElementAttributes = 131328, + CaseOrDefaultClauseStatements = 81985, + HeritageClauseTypes = 272, + SourceFileStatements = 65537, + Decorators = 24577, + TypeArguments = 26896, + TypeParameters = 26896, + Parameters = 1296, + IndexSignatureParameters = 4432, + } } declare namespace ts { const versionMajorMinor = "2.7"; @@ -2725,26 +2830,14 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - /** - * Partial interface of the System thats needed to support the caching of directory structure - */ - interface DirectoryStructureHost { + interface System { + args: string[]; newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - exit(exitCode?: number): void; - } - interface System extends DirectoryStructureHost { - args: string[]; getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2752,7 +2845,13 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2760,9 +2859,11 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; + exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; + clearScreen?(): void; } interface FileWatcher { close(): void; @@ -2791,7 +2892,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -2811,8 +2912,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; @@ -2968,7 +3071,7 @@ declare namespace ts { function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; - function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; @@ -3160,6 +3263,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -3235,13 +3339,13 @@ declare namespace ts { declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ - function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; - function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; + function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -3710,18 +3814,7 @@ declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } declare namespace ts { - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } -} -declare namespace ts { - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -3749,6 +3842,258 @@ declare namespace ts { */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} +declare namespace ts { + type AffectedFileResult = { + result: T; + affected: SourceFile | Program; + } | undefined; + interface BuilderProgramHost { + /** + * return true if file names are treated with case sensitivity + */ + useCaseSensitiveFileNames(): boolean; + /** + * If provided this would be used this hash instead of actual file shape text for detecting changes + */ + createHash?: (data: string) => string; + /** + * When emit or emitNextAffectedFile are called without writeFile, + * this callback if present would be used to write files + */ + writeFile?: WriteFileCallback; + } + /** + * Builder to manage the program state changes + */ + interface BuilderProgram { + /** + * Returns current program + */ + getProgram(): Program; + /** + * Get compiler options of the program + */ + getCompilerOptions(): CompilerOptions; + /** + * Get the source file in the program with file name + */ + getSourceFile(fileName: string): SourceFile | undefined; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Get the diagnostics for compiler options + */ + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics that dont belong to any file + */ + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the syntax diagnostics, for all source files if source file is not supplied + */ + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get all the dependencies of the file + */ + getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + /** + * Get the current directory of the program + */ + getCurrentDirectory(): string; + } + /** + * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files + */ + interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Gets the semantic diagnostics from the program for the next affected file and caches it + * Returns undefined if the iteration is complete + */ + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + } + /** + * The builder that can handle the changes in program and iterate through changed file to emit the files + * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files + */ + interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; + } + /** + * Create the builder to manage semantic diagnostics and cache them + */ + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + /** + * Create the builder that can handle the changes in program and iterate through changed files + * to emit the those files and manage semantic diagnostics cache as well + */ + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + /** + * Creates a builder thats just abstraction over program and can be used with watch + */ + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram): BuilderProgram; +} +declare namespace ts { + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string) => void; + type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; + interface WatchCompilerHost { + /** + * Used to create the program when need for program creation or recreation detected + */ + createProgram: CreateProgram; + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string): void; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + createHash?(data: string): string; + /** + * Use to check file presence for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + fileExists(path: string): boolean; + /** + * Use to read file text for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + readFile(path: string, encoding?: string): string | undefined; + /** If provided, used for module resolution as well as to handle directory structure */ + directoryExists?(path: string): boolean; + /** If provided, used in resolutions as well as handling directory structure */ + getDirectories?(path: string): string[]; + /** If provided, used to cache and handle directory structure modifications */ + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + /** Symbol links resolution */ + realpath?(path: string): string; + /** If provided would be used to write log about compilation */ + trace?(s: string): void; + /** If provided is used to get the environment variable */ + getEnvironmentVariable?(name: string): string; + /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + /** + * Host to create watch with root files and options + */ + interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { + /** root files to use to generate program */ + rootFiles: string[]; + /** Compiler options */ + options: CompilerOptions; + } + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports the diagnostics in reading/writing or parsing of the config file + */ + onConfigFileDiagnostic: DiagnosticReporter; + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Host to create watch with config file + */ + interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { + /** Name of the config file to compile */ + configFileName: string; + /** Options to extend */ + optionsToExtend?: CompilerOptions; + /** + * Used to generate source file names from the config file and its include, exclude, files rules + * and also to cache the directory stucture + */ + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + } + interface Watch { + /** Synchronize with host and get updated program */ + getProgram(): T; + } + /** + * Creates the watch what generates program using the config file + */ + interface WatchOfConfigFile extends Watch { + } + /** + * Creates the watch that generates program using the root files and compiler options + */ + interface WatchOfFilesAndCompilerOptions extends Watch { + /** Updates the root files in the program, only if this is not config file compilation */ + updateRootFileNames(fileNames: string[]): void; + } + /** + * Create the watch compiler host for either configFile or fileNames and its options + */ + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + /** + * Creates the watch from the host for root files and compiler options + */ + function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for config file + */ + function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; +} declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; /** @@ -3924,6 +4269,7 @@ declare namespace ts { useCaseSensitiveFileNames?(): boolean; readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; @@ -3982,7 +4328,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; 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[]; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -3998,8 +4345,13 @@ declare namespace ts { getProgram(): Program; dispose(): void; } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4074,6 +4426,17 @@ declare namespace ts { */ commands?: CodeActionCommand[]; } + interface CodeFixAction extends CodeAction { + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands: ReadonlyArray | undefined; + } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } @@ -4210,6 +4573,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4227,6 +4591,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4342,6 +4707,7 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: string; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -4508,6 +4874,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", + optionalModifier = "optional", } enum ClassificationTypeNames { comment = "comment", @@ -4653,9 +5020,6 @@ declare namespace ts { declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.7"; - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; diff --git a/lib/typescript.js b/lib/typescript.js index 1fbae487f8038..b4f8d26c1fab5 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -489,14 +489,19 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; (function (TokenFlags) { @@ -510,8 +515,9 @@ var ts; TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; - TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { @@ -556,47 +562,77 @@ var ts; // Diagnostics were produced and outputs were generated in spite of them. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // empty space NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; // Error handling - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; // State - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; // even though `T` can't be accessed in the current scope. - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -604,12 +640,14 @@ var ts; // Write symbols's type argument if it is instantiated symbol // eg. class C { p: T } <-- Show p as C.p here // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -745,6 +783,7 @@ var ts; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -871,6 +910,7 @@ var ts; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -894,11 +934,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1181,6 +1219,8 @@ var ts; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -1198,20 +1238,22 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; // Masks // - Additional bitmasks TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; @@ -1248,6 +1290,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1294,6 +1337,78 @@ var ts; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1396,7 +1511,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1409,6 +1524,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -1552,6 +1668,9 @@ var ts; ts.forEach = forEach; /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -1561,6 +1680,19 @@ var ts; return undefined; } ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1577,13 +1709,27 @@ var ts; ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { var result = []; - Debug.assert(arrayA.length === arrayB.length); + Debug.assertEqual(arrayA.length, arrayB.length); for (var i = 0; i < arrayA.length; i++) { result.push(callback(arrayA[i], arrayB[i], i)); } return result; } ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; function zipToMap(keys, values) { Debug.assert(keys.length === values.length); var map = createMap(); @@ -1666,17 +1812,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -1748,11 +1883,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1824,25 +1960,33 @@ var ts; return result; } ts.flatMap = flatMap; - function flatMapIter(iter, mapfn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapfn(value); - if (res) { - if (isArray(res)) { - result.push.apply(result, res); - } - else { - result.push(res); + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); } - } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; } - return result; } - ts.flatMapIter = flatMapIter; + ts.flatMapIterator = flatMapIterator; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1865,12 +2009,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -1879,20 +2034,35 @@ var ts; return result; } ts.mapDefined = mapDefined; - function mapDefinedIter(iter, mapFn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapFn(value); - if (res !== undefined) { - result.push(res); + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } } - } - return result; + }; } - ts.mapDefinedIter = mapDefinedIter; + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2158,7 +2328,7 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // Note: we need the following type assertion because of GH #17069 + // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2665,6 +2835,9 @@ var ts; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -3069,7 +3242,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */) + if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) return 3; } // Per RFC 1738 'file' URI schema has the shape file:/// @@ -3149,11 +3322,6 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ - function moduleHasNonRelativeName(moduleName) { - return !ts.isExternalModuleNameRelative(moduleName); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -3176,7 +3344,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3236,7 +3406,7 @@ var ts; ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part @@ -3266,7 +3436,7 @@ var ts; } else { // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" + // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + ts.directorySeparator]; @@ -3285,7 +3455,7 @@ var ts; var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } // Find the component that differs @@ -3507,7 +3677,6 @@ var ts; function getSubPatternFromSpec(spec, basePath, usage, _a) { var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; - var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); var lastComponent = lastOrUndefined(components); @@ -3524,11 +3693,7 @@ var ts; for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { var component = components_1[_i]; if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - return undefined; - } subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; } else { if (usage === "directories") { @@ -3854,10 +4019,10 @@ var ts; } function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0 /* None */; this.modifierFlagsCache = 0 /* None */; this.transformFlags = 0 /* None */; @@ -3997,9 +4162,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; /** @@ -4118,182 +4281,20 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - /** - * If the readDirectory result was already cached, it returns that - * Otherwise gets result from host and caches it. - * The host request is done under try catch block to avoid caching incorrect result - */ - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - // If there is exception to read directories, dont cache the result and direct the calls to host - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - // Just clear the cache for now - // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated - clearCache(); - } - else { - // This was earlier a file (hence not in cached directory contents) - // or we never cached the directory containing it - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - // Folder added or removed, clear the cache instead of updating the folder and its structure - clearCache(); - } - else { - // No need to update the directory structure, just files - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.singleElementArray = singleElementArray; })(ts || (ts = {})); /// var ts; @@ -4568,7 +4569,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -4601,6 +4602,9 @@ var ts; return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } var nodeSystem = { + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -4685,7 +4689,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -5022,6 +5031,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5136,6 +5147,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -5190,7 +5202,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -5278,6 +5290,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5356,6 +5369,10 @@ var ts; Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5442,7 +5459,6 @@ var ts; The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), @@ -5493,6 +5509,7 @@ var ts; Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), @@ -5533,7 +5550,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -5640,6 +5657,9 @@ var ts; Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5668,6 +5688,9 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5743,9 +5766,9 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -5757,6 +5780,9 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); /// @@ -5904,7 +5930,7 @@ var ts; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: - Can contain Unicode 3.0.0 categories: + Can contain Unicode 3.0.0 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5912,7 +5938,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: = - Can contain IdentifierStart + Unicode 3.0.0 categories: + Can contain IdentifierStart + Unicode 3.0.0 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), or @@ -5926,7 +5952,7 @@ var ts; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers IdentifierStart :: - Can contain Unicode 6.2 categories: + Can contain Unicode 6.2 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5934,7 +5960,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: - Can contain IdentifierStart + Unicode 6.2 categories: + Can contain IdentifierStart + Unicode 6.2 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), @@ -6253,7 +6279,7 @@ var ts; } function scanConflictMarkerTrivia(text, pos, error) { if (error) { - error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); } var ch = text.charCodeAt(pos); var len = text.length; @@ -6509,19 +6535,60 @@ var ts; lookAhead: lookAhead, scanRange: scanRange, }; - function error(message, length) { + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } if (onError) { + var oldPos = pos; + pos = errPos; onError(message, length || 0); + pos = oldPos; } } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } function scanNumber() { var start = pos; - while (isDigit(text.charCodeAt(pos))) - pos++; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; if (text.charCodeAt(pos) === 46 /* dot */) { pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; + decimalFragment = scanNumberFragment(); } var end = pos; if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { @@ -6529,17 +6596,29 @@ var ts; tokenFlags |= 16 /* Scientific */; if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) pos++; - if (isDigit(text.charCodeAt(pos))) { - pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; - end = pos; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); } else { - error(ts.Diagnostics.Digit_expected); + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; } } - return "" + +(text.substring(start, end)); + if (tokenFlags & 512 /* ContainsSeparator */) { + var result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + return "" + +result; + } + else { + return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + } } function scanOctalDigits() { var start = pos; @@ -6552,21 +6631,39 @@ var ts; * Scans the given number of hexadecimal digits in the text, * returning -1 if the given number is unavailable. */ - function scanExactNumberOfHexDigits(count) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); } /** * Scans as many hexadecimal digits as are available in the text, * returning -1 if the given number of digits was unavailable. */ - function scanMinimumNumberOfHexDigits(count) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true); + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } - function scanHexDigits(minCount, scanAsManyAsPossible) { + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { var digits = 0; var value = 0; + var allowSeparator = false; + var isPreviousTokenSeparator = false; while (digits < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { value = value * 16 + ch - 48 /* _0 */; } @@ -6581,10 +6678,14 @@ var ts; } pos++; digits++; + isPreviousTokenSeparator = false; } if (digits < minCount) { value = -1; } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return value; } function scanString(jsxAttributeString) { @@ -6735,7 +6836,7 @@ var ts; } } function scanHexadecimalEscape(numDigits) { - var escapedValue = scanExactNumberOfHexDigits(numDigits); + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); } @@ -6745,7 +6846,7 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1); + var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -6789,7 +6890,7 @@ var ts; if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { var start_1 = pos; pos += 2; - var value = scanExactNumberOfHexDigits(4); + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); pos = start_1; return value; } @@ -6841,8 +6942,27 @@ var ts; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. var numberOfDigits = 0; + var separatorAllowed = false; + var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); + // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; var valueOfCh = ch - 48 /* _0 */; if (!isDigit(ch) || valueOfCh >= base) { break; @@ -6850,11 +6970,17 @@ var ts; value = value * base + valueOfCh; pos++; numberOfDigits++; + isPreviousTokenSeparator = false; } // Invalid binaryIntegerLiteral or octalIntegerLiteral if (numberOfDigits === 0) { return -1; } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + return value; + } return value; } function scan() { @@ -7044,7 +7170,7 @@ var ts; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1); + var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); if (value < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -7390,7 +7516,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -7413,6 +7539,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: @@ -7423,55 +7550,30 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - pos++; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - pos++; return token = 39 /* AsteriskToken */; case 123 /* openBrace */: - pos++; return token = 17 /* OpenBraceToken */; case 125 /* closeBrace */: - pos++; return token = 18 /* CloseBraceToken */; case 91 /* openBracket */: - pos++; return token = 21 /* OpenBracketToken */; case 93 /* closeBracket */: - pos++; return token = 22 /* CloseBracketToken */; case 60 /* lessThan */: - pos++; return token = 27 /* LessThanToken */; - case 62 /* greaterThan */: - pos++; - return token = 29 /* GreaterThanToken */; case 61 /* equals */: - pos++; return token = 58 /* EqualsToken */; case 44 /* comma */: - pos++; return token = 26 /* CommaToken */; case 46 /* dot */: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24 /* DotDotDotToken */; - } return token = 23 /* DotToken */; - case 33 /* exclamation */: - pos++; - return token = 51 /* ExclamationToken */; - case 63 /* question */: - pos++; - return token = 55 /* QuestionToken */; } if (isIdentifierStart(ch, 6 /* Latest */)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } @@ -7479,7 +7581,7 @@ var ts; return token = 71 /* Identifier */; } else { - return pos += 1, token = 0 /* Unknown */; + return token = 0 /* Unknown */; } } function speculationHelper(callback, isLookahead) { @@ -7560,8 +7662,9 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.emptyArray = []; + ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -7581,15 +7684,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str += " "; }, @@ -7603,10 +7715,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -7640,12 +7752,19 @@ var ts; return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -7866,7 +7985,7 @@ var ts; function getLiteralText(node, sourceFile) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent) { + if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; @@ -8306,7 +8425,7 @@ var ts; return node === parent.type; case 182 /* CallExpression */: case 183 /* NewExpression */: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -8892,11 +9011,6 @@ var ts; (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")'). - * This function does not test if the node is in a JavaScript file or not. - */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 182 /* CallExpression */) { return false; @@ -9055,41 +9169,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 /* ModuleDeclaration */ && node.body && node.body.kind === 234 /* ModuleDeclaration */ && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -9120,7 +9223,7 @@ var ts; if (node.kind === 147 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -9230,6 +9333,33 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208 /* Block */: + case 209 /* VariableStatement */: + case 221 /* WithStatement */: + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -9579,6 +9709,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; /** * Includes the word "Symbol" with unicode escapes */ @@ -10011,7 +10145,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -10206,7 +10352,7 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (node.type) { + if (ts.hasType(node)) { return node.type; } if (checkJSDoc || isInJavaScriptFile(node)) { @@ -10651,14 +10797,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -11021,6 +11167,10 @@ var ts; return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11227,8 +11377,8 @@ var ts; // // { // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; @@ -11879,7 +12029,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192 /* AwaitExpression */; + return node.kind === 190 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -12352,7 +12502,7 @@ var ts; /* @internal */ function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; // Keywords @@ -12466,6 +12616,18 @@ var ts; return node && (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */); } ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; // Type members function isTypeElement(node) { var kind = node.kind; @@ -13020,6 +13182,39 @@ var ts; return !!node.jsDoc && node.jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); /// /// @@ -13109,20 +13304,48 @@ var ts; case 267 /* SpreadAssignment */: return visitNode(cbNode, node.expression); case 147 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 150 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 149 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 265 /* PropertyAssignment */: - case 227 /* VariableDeclaration */: - case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 227 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); + case 177 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 161 /* FunctionType */: case 162 /* ConstructorType */: case 156 /* CallSignature */: @@ -13572,7 +13795,7 @@ var ts; // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost // all nodes would need extra state on them to store this info. // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 // grammar specification. // // An important thing about these context concepts. By default they are effectively inherited @@ -13750,15 +13973,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -14295,9 +14510,13 @@ var ts; return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); case 18 /* TypeParameters */: return isIdentifier(); - case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + if (token() === 26 /* CommaToken */) { + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 19 /* TypeArguments */: @@ -14317,7 +14536,7 @@ var ts; function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not + // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // // extends {} { @@ -14401,7 +14620,7 @@ var ts; } function isVariableDeclaratorListTerminator() { // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } @@ -14506,6 +14725,10 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -14904,7 +15127,7 @@ var ts; // We also do not need to check for negatives because any prefix operator would be part of a // parent unary expression. if (node.kind === 8 /* NumericLiteral */) { - node.numericLiteralFlags = scanner.getTokenFlags() & 496 /* NumericLiteralFlags */; + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; } nextToken(); finishNode(node); @@ -15014,7 +15237,7 @@ var ts; // // // - // We do *not* want to consume the > as we're consuming the expression for "". + // We do *not* want to consume the `>` as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } @@ -15754,7 +15977,7 @@ var ts; // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". // // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { @@ -15781,7 +16004,7 @@ var ts; // we're in '2' or '3'. Consume the assignment and return. // // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= + // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } @@ -15912,7 +16135,7 @@ var ts; var second = nextToken(); if (first === 19 /* OpenParenToken */) { if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". + // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. @@ -16113,7 +16336,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -16475,7 +16700,8 @@ var ts; // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" // For example: // var foo3 = require("subfolder - // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; expression = parseTokenNode(); } @@ -16523,7 +16749,7 @@ var ts; // treated as the invocation of "new Foo". We disambiguate that in code (to match // the original grammar) by making sure that if we see an ObjectCreationExpression // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think + // object creation only, and not at all as an invocation. Another way to think // about this is that for every "new" that we see, we will consume an argument list if // it is there as part of the *associated* object creation node. Any additional // argument lists we see, will become invocation expressions. @@ -16887,7 +17113,7 @@ var ts; } var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. + // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } // If we have a '<', then only parse this as a argument list if the type arguments @@ -17801,8 +18027,8 @@ var ts; // off. The grammar would look something like this: // // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. node.initializer = ts.hasModifier(node, 32 /* Static */) @@ -17884,6 +18110,7 @@ var ts; switch (token()) { case 19 /* OpenParenToken */: // Method declaration case 27 /* LessThanToken */: // Generic Method declaration + case 51 /* ExclamationToken */: // Non-null assertion on property name case 56 /* ColonToken */: // Type Annotation for declaration case 58 /* EqualsToken */: // Initializer for declaration case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on. @@ -18563,7 +18790,6 @@ var ts; scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. - var advanceToken = true; var state = 1 /* SawAsterisk */; var margin = undefined; // + 4 for leading '/** ' @@ -18575,17 +18801,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5 /* WhitespaceTrivia */) { + t = nextJSDocToken(); } - if (token() === 4 /* NewLineTrivia */) { + if (t === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + loop: while (true) { + switch (t) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); @@ -18594,7 +18820,6 @@ var ts; // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` state = 0 /* BeginningOfLine */; - advanceToken = false; margin = undefined; indent++; } @@ -18639,19 +18864,14 @@ var ts; indent += whitespace.length; break; case 1 /* EndOfFileToken */: - break; + break loop; default: // anything other than whitespace or asterisk at the beginning of the line starts the comment text state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -18736,7 +18956,8 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -18749,8 +18970,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { state = 0 /* BeginningOfLine */; @@ -18759,8 +18981,11 @@ var ts; indent = 0; break; case 57 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: // Done - break; + break loop; case 5 /* WhitespaceTrivia */: if (state === 2 /* SavingComments */) { pushComment(scanner.getTokenText()); @@ -18778,7 +19003,7 @@ var ts; if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; + indent += 1; break; } // record the * as a comment @@ -18788,15 +19013,11 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281 /* JSDocTag */, atToken.pos); @@ -18804,8 +19025,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -18876,10 +19096,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); @@ -18985,10 +19202,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -19033,8 +19247,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); @@ -19074,34 +19287,44 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0 /* Property */; + break; case "arg": case "argument": case "param": - return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1 /* Parameter */; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146 /* TypeParameter */); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -19120,6 +19343,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17 /* OpenBraceToken */); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -19298,7 +19529,7 @@ var ts; // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have + // depend if delta is positive or negative. If delta is positive then we have // something like: // // -------------------AAA----------------- @@ -19322,7 +19553,7 @@ var ts; element.pos = Math.min(element.pos, changeRangeNewEnd); // If the 'end' is after the change range, then we always adjust it by the delta // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we + // will depend on if delta is positive or negative. If delta is positive then we // have something like: // // -------------------AAA----------------- @@ -19908,7 +20139,7 @@ var ts; // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -20331,7 +20562,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 /* StringLiteral */ || expr2.kind === 13 /* NoSubstitutionTemplateLiteral */); + } + function isNarrowableInOperands(left, right) { + return (left.kind === 9 /* StringLiteral */ || left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -20345,6 +20579,8 @@ var ts; isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 93 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); + case 92 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); case 26 /* CommaToken */: return isNarrowingExpression(expr.right); } @@ -21136,7 +21372,7 @@ var ts; // to the one we would get for: { <...>(...): T } // // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072 /* Signature */); @@ -21724,27 +21960,13 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' // is still pointing to 'module.exports'. // We do not want to consider this as 'export=' since a module can have only one of these. // Similarly we do not want to treat 'module.exports = exports' as an 'export='. var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { // Mark it as a module in case there are no other exports in the file setCommonJsModuleIndicator(node); return; @@ -21815,7 +22037,7 @@ var ts; if (node.kind === 195 /* BinaryExpression */) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { // This can be an alias for the 'exports' or 'module.exports' names, e.g. // var util = module.exports; // util.property = function ... @@ -21827,11 +22049,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -21947,7 +22165,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); @@ -22041,6 +22259,29 @@ var ts; return true; } } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } /** * Computes the transform flags for a node, given the transform flags of its subtree * @@ -22101,6 +22342,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); + case 181 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -22109,15 +22352,19 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; @@ -22128,19 +22375,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 180 /* PropertyAccessExpression */: - case 181 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22153,7 +22388,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22174,7 +22409,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22203,7 +22438,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; + return transformFlags & ~939525441 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22223,7 +22458,7 @@ var ts; transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -22249,7 +22484,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. @@ -22266,7 +22501,7 @@ var ts; transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22284,7 +22519,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22295,7 +22530,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -22307,7 +22542,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22321,7 +22556,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -22348,7 +22583,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22366,7 +22601,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -22377,7 +22612,7 @@ var ts; transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -22421,7 +22656,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22453,7 +22688,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -22478,19 +22713,31 @@ var ts; transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22504,7 +22751,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -22520,7 +22767,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22530,7 +22777,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22539,7 +22786,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22550,7 +22797,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -22559,7 +22806,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; + return transformFlags & ~977327425 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -22571,18 +22818,25 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; + var excludeFlags = 939525441 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: @@ -22591,8 +22845,6 @@ var ts; case 76 /* ConstKeyword */: case 233 /* EnumDeclaration */: case 268 /* EnumMember */: - case 185 /* TypeAssertionExpression */: - case 203 /* AsExpression */: case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. @@ -22709,7 +22961,8 @@ var ts; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. @@ -22720,11 +22973,11 @@ var ts; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; @@ -22737,7 +22990,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; case 179 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; + excludeFlags = 942740801 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. @@ -22756,7 +23009,7 @@ var ts; break; case 178 /* ArrayLiteralExpression */: case 183 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. @@ -22802,27 +23055,27 @@ var ts; case 182 /* CallExpression */: case 183 /* NewExpression */: case 178 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; case 234 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; + return 977327425 /* ModuleExcludes */; case 147 /* Parameter */: - return 536872257 /* ParameterExcludes */; + return 939525441 /* ParameterExcludes */; case 188 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; + return 1003902273 /* ArrowFunctionExcludes */; case 187 /* FunctionExpression */: case 229 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; + return 1003935041 /* FunctionExcludes */; case 228 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; + return 948962625 /* VariableDeclarationListExcludes */; case 230 /* ClassDeclaration */: case 200 /* ClassExpression */: - return 539358529 /* ClassExcludes */; + return 942011713 /* ClassExcludes */; case 153 /* Constructor */: - return 601015617 /* ConstructorExcludes */; + return 1003668801 /* ConstructorExcludes */; case 152 /* MethodDeclaration */: case 154 /* GetAccessor */: case 155 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; + return 1003668801 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: case 130 /* NeverKeyword */: @@ -22841,14 +23094,23 @@ var ts; case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 179 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; + return 942740801 /* ObjectLiteralExcludes */; case 264 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; + return 940574017 /* CatchClauseExcludes */; case 175 /* ObjectBindingPattern */: case 176 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; + return 940049729 /* BindingPatternExcludes */; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + case 186 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; default: - return 536872257 /* NodeExcludes */; + return 939525441 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -22864,7 +23126,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -22960,8 +23222,9 @@ var ts; visitType(type.modifiersType); } function visitSignature(signature) { - if (signature.typePredicate) { - visitType(signature.typePredicate.type); + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); } ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { @@ -23067,9 +23330,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -23623,8 +23886,8 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { @@ -23641,11 +23904,17 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - if (!compilerOptions.preserveSymlinks) { - resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + var originalPath = void 0; + if (!compilerOptions.preserveSymlinks && resolvedValue) { + originalPath = resolvedValue.path; + var path = realPath(resolved_1.value.path, host, traceEnabled); + if (path === originalPath) { + originalPath = undefined; + } + resolvedValue = __assign({}, resolvedValue, { path: path }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -23681,7 +23950,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -23695,6 +23966,49 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } /* @internal */ function directoryProbablyExists(directoryName, host) { // if host does not support 'directoryExists' assume that directory will exist @@ -23780,18 +24094,41 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { - var host = _a.host, traceEnabled = _a.traceEnabled; + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); + if (subModuleName === "") { + var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + } + else { + var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); + if (typeof jsPath === "string") { + subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -23949,13 +24286,18 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + /* @internal */ + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -23971,7 +24313,8 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { @@ -24016,7 +24359,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -24146,6 +24489,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -24179,16 +24527,32 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { node = ts.getParseTreeNode(node, ts.isExpression); return node ? getContextualType(node) : undefined; }, + isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { node = ts.getParseTreeNode(node, ts.isCallLikeExpression); @@ -24203,7 +24567,11 @@ var ts; }, isValidPropertyAccess: function (node, propertyName) { node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (node, type, property) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); }, getSignatureFromDeclaration: function (declaration) { declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); @@ -24227,7 +24595,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -24269,11 +24637,17 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -24319,13 +24693,15 @@ var ts; var markerSubType = createType(32768 /* TypeParameter */); markerSubType.constraint = markerSuperType; var markerOtherType = createType(32768 /* TypeParameter */); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var reverseMappedCache = ts.createMap(); var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -24492,20 +24868,20 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - var _displayBuilder; var TypeSystemPropertyName; (function (TypeSystemPropertyName) { TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { CheckMode[CheckMode["Normal"] = 0] = "Normal"; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; })(CheckMode || (CheckMode = {})); var CallbackCheck; (function (CallbackCheck) { @@ -24535,6 +24911,142 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + /** + * @deprecated + */ + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -24550,10 +25062,12 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -24812,7 +25326,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage @@ -24900,10 +25414,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -24963,7 +25478,7 @@ var ts; if (location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. - if (result = moduleExports.get("default")) { + if (result = moduleExports.get("default" /* Default */)) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { break loop; @@ -25119,14 +25634,14 @@ var ts; } break; } - if (location.kind !== 208 /* Block */) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. - // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // If `result === lastNonBlockLocation.symbol`, that means that we are somewhere inside `lastNonBlockLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; @@ -25138,7 +25653,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -25201,6 +25718,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -25369,6 +25900,41 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a default member specified + if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -25377,15 +25943,15 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -25465,7 +26031,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } var symbol = symbolFromModule && symbolFromVariable ? @@ -25717,7 +26283,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -25752,8 +26318,42 @@ var ts; // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -25806,7 +26406,7 @@ var ts; if (!source) return; source.forEach(function (sourceSymbol, id) { - if (id === "default") + if (id === "default" /* Default */) return; var targetSymbol = target.get(id); if (!targetSymbol) { @@ -25991,11 +26591,14 @@ var ts; } var visitedSymbolTables = []; return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols) { + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols); + var result = trySymbolTable(symbols, ignoreQualification); visitedSymbolTables.pop(); return result; } @@ -26005,20 +26608,20 @@ var ts; // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function isUMDExportSymbol(symbol) { return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } - function trySymbolTable(symbols) { + function trySymbolTable(symbols, ignoreQualification) { // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.escapedName))) { + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; } // Check if symbol is any of the alias @@ -26029,12 +26632,13 @@ var ts; // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; } // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -26089,6 +26693,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -26216,97 +26824,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 3112960 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 162 /* ConstructorType */ : 161 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 157 /* ConstructSignature */ : 156 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8 /* NoTruncation */) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256 /* UseFullyQualifiedType */) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096 /* SuppressAnyReturnType */) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1 /* WriteArrayAsGenericType */) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64 /* WriteTypeArgumentsOfSignature */) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; return undefined; @@ -26343,6 +26985,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); } if (type.flags & 2048 /* Void */) { @@ -26364,10 +27011,13 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -26381,7 +27031,7 @@ var ts; // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -26394,7 +27044,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } return undefined; @@ -26420,7 +27070,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); @@ -26429,7 +27079,7 @@ var ts; var symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); @@ -26452,10 +27102,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + if (isConstructorObject) { + return createTypeNodeFromObjectType(type); + } + else { + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } } } else { @@ -26472,7 +27128,8 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -26497,11 +27154,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304 /* InObjectTypeLiteral */; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); @@ -26515,7 +27172,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -26529,12 +27186,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -26613,7 +27275,10 @@ var ts; typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); + var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? + createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : + resolvedType.stringIndexInfo; + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -26624,9 +27289,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + } + } var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -26673,20 +27353,30 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); } var returnTypeNode; - if (signature.typePredicate) { - var typePredicate = signature.typePredicate; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : ts.createThisTypeNode(); @@ -26697,7 +27387,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256 /* SuppressAnyReturnType */) { if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { returnTypeNode = undefined; } @@ -26705,14 +27395,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -26723,7 +27416,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -26749,47 +27442,22 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -26817,11 +27485,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -26884,6 +27634,9 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -26893,7 +27646,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } switch (declaration.kind) { @@ -26912,882 +27665,161 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } + return links.isVisible; } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 177 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 227 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + // falls through + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 229 /* FunctionDeclaration */: + case 233 /* EnumDeclaration */: + case 238 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 238 /* ImportEqualsDeclaration */ && parent.kind !== 269 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { + return isGlobalSourceFile(parent); } - } - else if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || - // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 153 /* Constructor */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: + case 147 /* Parameter */: + case 235 /* ModuleBlock */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 160 /* TypeReference */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 146 /* TypeParameter */: + // Source file and namespace export are always visible + case 269 /* SourceFile */: + case 237 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 244 /* ExportAssignment */: + return false; + default: + return false; } } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 33585807 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - // In a literal enum type with a single member E { A }, E and E.A denote the - // same type. We always display this type simply as E. - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - } - else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024 /* UniqueESSymbol */) { - if (flags & 131072 /* AllowUniqueESSymbolType */) { - writeKeyword(writer, 140 /* UniqueKeyword */); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137 /* SymbolKeyword */); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288 /* Index */) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128 /* InElementType */); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - else if (type.flags & 1048576 /* IndexedAccess */) { - writeType(type.objectType, 128 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 244 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + } + else if (node.parent.kind === 247 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; } else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + result = result || []; + ts.pushIfUnique(result, resultNode); } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); } - writePunctuation(writer, 29 /* GreaterThanToken */); } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { - writeAnonymousType(type, flags); - } - else { - // Write the type reference in the format f.g.C where A and B are type arguments - // for outer type parameters, and f and g are the respective declaring containers of those - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - // When type parameters are their own type arguments for the whole group (i.e. we have - // the default outer type arguments), we don't show the group. - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 131072 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - // If type is an anonymous type literal in a type alias declaration, use type alias name - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - else { - // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead - // of types allows us to catch circular references to instantiations of the same anonymous type - // However, in case of class expressions, we want to write both the static side and the instance side. - // We skip adding the static side so that the instance side has a chance to be written - // before checking for circular references. - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || // is exported function symbol - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it - ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128 /* InElementType */) { - return true; - } - else if (flags & 512 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { - if (p.flags & 4194304 /* Prototype */) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 512 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 16 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } - function isDeclarationVisible(node) { - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } - return false; - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 177 /* BindingElement */: - return isDeclarationVisible(node.parent.parent); - case 227 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - // If the binding pattern is empty, this variable declaration is not visible - return false; - } - // falls through - case 234 /* ModuleDeclaration */: - case 230 /* ClassDeclaration */: - case 231 /* InterfaceDeclaration */: - case 232 /* TypeAliasDeclaration */: - case 229 /* FunctionDeclaration */: - case 233 /* EnumDeclaration */: - case 238 /* ImportEqualsDeclaration */: - // external module augmentation is always visible - if (ts.isExternalModuleAugmentation(node)) { - return true; - } - var parent = getDeclarationContainer(node); - // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 238 /* ImportEqualsDeclaration */ && parent.kind !== 269 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { - return isGlobalSourceFile(parent); - } - // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent); - case 150 /* PropertyDeclaration */: - case 149 /* PropertySignature */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - case 152 /* MethodDeclaration */: - case 151 /* MethodSignature */: - if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { - // Private/protected properties/methods are not visible - return false; - } - // Public properties/methods are visible if its parents are visible, so: - // falls through - case 153 /* Constructor */: - case 157 /* ConstructSignature */: - case 156 /* CallSignature */: - case 158 /* IndexSignature */: - case 147 /* Parameter */: - case 235 /* ModuleBlock */: - case 161 /* FunctionType */: - case 162 /* ConstructorType */: - case 164 /* TypeLiteral */: - case 160 /* TypeReference */: - case 165 /* ArrayType */: - case 166 /* TupleType */: - case 167 /* UnionType */: - case 168 /* IntersectionType */: - case 169 /* ParenthesizedType */: - return isDeclarationVisible(node.parent); - // Default binding, import specifier and namespace import is visible - // only on demand so by default it is not visible - case 240 /* ImportClause */: - case 241 /* NamespaceImport */: - case 243 /* ImportSpecifier */: - return false; - // Type parameters are always visible - case 146 /* TypeParameter */: - // Source file and namespace export are always visible - case 269 /* SourceFile */: - case 237 /* NamespaceExportDeclaration */: - return true; - // Export assignments do not create name bindings outside the module - case 244 /* ExportAssignment */: - return false; - default: - return false; - } - } - } - function collectLinkedAliases(node, setVisibility) { - var exportSymbol; - if (node.parent && node.parent.kind === 244 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); - } - else if (node.parent.kind === 247 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); - } - var result; - if (exportSymbol) { - buildVisibleNodeList(exportSymbol.declarations); - } - return result; - function buildVisibleNodeList(declarations) { - ts.forEach(declarations, function (declaration) { - var resultNode = getAnyImportSyntax(declaration) || declaration; - if (setVisibility) { - getNodeLinks(declaration).isVisible = true; - } - else { - result = result || []; - ts.pushIfUnique(result, resultNode); - } - if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { - // Add the referenced top container visible - var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); - if (importSymbol) { - buildVisibleNodeList(importSymbol.declarations); - } - } - }); - } - } - /** - * Push an entry on the type resolution stack. If an entry with the given target and the given property name - * is already on the stack, and no entries in between already have a type, then a circularity has occurred. - * In this case, the result values of the existing entry and all entries pushed after it are changed to false, - * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. - * In order to see if the same query has already been done before, the target object and the propertyName both - * must match the one passed in. - * - * @param target The symbol, type, or signature whose type is being queried - * @param propertyName The property name that should be used to query the target for its type - */ - function pushTypeResolution(target, propertyName) { - var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); - if (resolutionCycleStartIndex >= 0) { - // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { - resolutionResults[i] = false; - } - return false; - } - resolutionTargets.push(target); - resolutionResults.push(/*items*/ true); - resolutionPropertyNames.push(propertyName); - return true; - } - function findResolutionCycleStartIndex(target, propertyName) { - for (var i = resolutionTargets.length - 1; i >= 0; i--) { - if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { - return -1; - } - if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { - return i; + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; } } return -1; @@ -27805,6 +27837,10 @@ var ts; if (propertyName === 3 /* ResolvedReturnType */) { return target.resolvedReturnType; } + if (propertyName === 4 /* ResolvedBaseConstraint */) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will @@ -27929,7 +27965,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -27950,7 +27987,7 @@ var ts; } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -27971,7 +28008,7 @@ var ts; type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -27997,11 +28034,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === 216 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 216 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 217 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 217 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -28012,11 +28049,11 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } + var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; // Use type from type annotation if one is present - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, /*optional*/ !!declaration.questionToken && includeOptionality); + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && declaration.kind === 227 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && @@ -28058,23 +28095,19 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for return trueType; } - // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 266 /* ShorthandPropertyAssignment */) { - return checkIdentifier(declaration.name); - } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); @@ -28121,7 +28154,7 @@ var ts; types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } } - var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + var type = jsDocType || getUnionType(types, 2 /* Subtype */); return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if @@ -28215,19 +28248,13 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 1024 /* UniqueESSymbol */ && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 1024 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } - // During a normal type check we'll never get to here with a property assignment (the check of the containing - // object literal uses a different path). We exclude widening only so that language services and type verification - // tools see the actual type. - if (declaration.kind === 265 /* PropertyAssignment */) { - return type; - } return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any - type = declaration.dotDotDotToken ? anyArrayType : anyType; + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && noImplicitAny) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { @@ -28241,6 +28268,12 @@ var ts; var memberDeclaration = root.kind === 147 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { @@ -28274,9 +28307,39 @@ var ts; declaration.kind === 180 /* PropertyAccessExpression */ && declaration.parent.kind === 195 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else { + else if (ts.isJSDocPropertyTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } + else { + ts.Debug.fail("Unhandled declaration kind! " + ts.SyntaxKind[declaration.kind]); + } if (!popTypeResolution()) { type = reportCircularityError(symbol); } @@ -28443,6 +28506,9 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { return getTypeOfVariableOrParameterOrProperty(symbol); } @@ -28656,10 +28722,10 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = ts.emptyArray; + type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); @@ -28682,22 +28748,29 @@ var ts; var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; + return type.resolvedBaseTypes = ts.emptyArray; } baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === unknownType) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); - return; + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; } - type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -28735,7 +28808,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); } } else { @@ -28900,7 +28973,7 @@ var ts; } } if (memberTypeList.length) { - var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); if (enumType_1.flags & 131072 /* Union */) { enumType_1.flags |= 256 /* EnumLiteral */; enumType_1.symbol = symbol; @@ -28998,7 +29071,7 @@ var ts; */ function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isThislessType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); } /** * A function-like declaration is considered free of `this` references if it has a return type @@ -29260,18 +29333,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -29301,6 +29375,7 @@ var ts; if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); var thisArgument = ts.lastOrUndefined(typeArguments); for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { var baseType = baseTypes_1[_i]; @@ -29328,27 +29403,28 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; + sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -29359,7 +29435,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -29418,13 +29494,13 @@ var ts; var s = signature; // Union the result types when more than one signature matches if (unionSignatures.length > 1) { - s = cloneSignature(signature); + var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); } - // Clear resolved return type we possibly got from cloneSignature - s.resolvedReturnType = undefined; + s = cloneSignature(signature); + s.thisParameter = thisParameter; s.unionSignatures = unionSignatures; } (result || (result = [])).push(s); @@ -29446,7 +29522,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union @@ -29542,6 +29618,7 @@ var ts; if (symbol.exports) { members = getExportsOfSymbol(symbol); } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -29573,6 +29650,23 @@ var ts; } } } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var readonlyMask = type.mappedType.declaration.readonlyToken ? false : true; + var optionalMask = type.mappedType.declaration.questionToken ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -29703,6 +29797,9 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } else if (type.objectFlags & 16 /* Anonymous */) { resolveAnonymousTypeMembers(type); } @@ -29794,12 +29891,17 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { + // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. + // to avoid this, return `undefined`. + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -29823,29 +29925,30 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; @@ -29865,7 +29968,7 @@ var ts; return stringType; } if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -29881,7 +29984,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -29943,15 +30046,14 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; - var types = containingType.types; var isUnion = containingType.flags & 131072 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var current = types_5[_i]; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -29982,8 +30084,8 @@ var ts; var propTypes = []; var declarations = []; var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -30096,7 +30198,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); + return getUnionType(propTypes, 2 /* Subtype */); } } return undefined; @@ -30154,7 +30256,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -30162,27 +30264,27 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 71 /* Identifier */) { - return { - kind: 1 /* Identifier */, - parameterName: parameterName ? parameterName.escapedText : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; + return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 + parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); } else { - return { - kind: 0 /* This */, - type: getTypeFromTypeNode(node.type) - }; + return createThisTypePredicate(type); } } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } /** * Gets the minimum number of type arguments needed to satisfy all non-optional type * parameters. @@ -30289,11 +30391,8 @@ var ts; : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -30303,7 +30402,7 @@ var ts; // b) It references `arguments` somewhere var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -30418,6 +30517,28 @@ var ts; return getTypeOfSymbol(signature.thisParameter); } } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var declaration = signature.declaration; + signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? + createTypePredicateFromTypePredicateNode(declaration.type) : + noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -30428,7 +30549,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } else { type = getReturnTypeFromBody(signature.declaration); @@ -30575,12 +30696,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -30601,8 +30722,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -30652,7 +30773,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) @@ -31093,14 +31214,14 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31165,7 +31286,8 @@ var ts; // expression constructs such as array literals and the || and ?: operators). Named types can // circularly reference themselves and therefore cannot be subtype reduced during their declaration. // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } if (types.length === 0) { return neverType; } @@ -31177,11 +31299,15 @@ var ts; if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsLiteralOrUniqueESSymbol) { - removeRedundantLiteralTypes(typeSet); + switch (unionReduction) { + case 1 /* Literal */: + if (typeSet.containsLiteralOrUniqueESSymbol) { + removeRedundantLiteralTypes(typeSet); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : @@ -31190,6 +31316,40 @@ var ts; } return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } // This function assumes the constituent type list is sorted and deduplicated. function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { @@ -31219,7 +31379,7 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } @@ -31252,8 +31412,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } @@ -31290,8 +31450,7 @@ var ts; // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), - /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); @@ -31320,7 +31479,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -31369,6 +31528,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -31442,42 +31602,64 @@ var ts; } return false; } + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // undefined if no transformation is possible. - function getTransformedIndexedAccessType(type) { + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); + if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a + // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen + // eventually anyway, but it easier to reason about. + if (ts.some(objectType.types, isMappedTypeToNever)) { + var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); + return getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { // If the index type is generic, or if the object type is generic and doesn't originate in an expression, // we are performing a higher-order index access where we cannot meaningfully access the properties of the @@ -31583,10 +31765,7 @@ var ts; if (right.flags & 131072 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 33554432 /* NonPrimitive */) { - return nonPrimitiveType; - } - if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */)) { + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */ | 33554432 /* NonPrimitive */)) { return left; } var members = ts.createSymbolTable(); @@ -31639,8 +31818,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= propagatedFlags; - spread.flags |= 2097152 /* FreshLiteral */ | 8388608 /* ContainsObjectLiteral */; + spread.flags |= propagatedFlags | 8388608 /* ContainsObjectLiteral */; spread.objectFlags |= (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } @@ -31860,7 +32038,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -31882,7 +32060,7 @@ var ts; result.target = typeParameter; return result; } - function cloneTypePredicate(predicate, mapper) { + function instantiateTypePredicate(predicate, mapper) { if (ts.isIdentifierTypePredicate(predicate)) { return { kind: 1 /* Identifier */, @@ -31900,7 +32078,6 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { // First create a fresh set of type parameters, then include a mapping from the old to the // new type parameters in the mapper function. Finally store this mapper in the new type @@ -31912,11 +32089,12 @@ var ts; tp.mapper = mapper; } } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), - /*resolvedReturnType*/ undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -32064,7 +32242,7 @@ var ts; } } if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { - return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return getUnionType(instantiateTypes(type.types, mapper), 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (type.flags & 262144 /* Intersection */) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); @@ -32269,7 +32447,7 @@ var ts; // with respect to T. var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -32289,11 +32467,13 @@ var ts; } var sourceReturnType = getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); } @@ -32408,7 +32588,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -32493,6 +32673,9 @@ var ts; } return false; } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return source.flags & 67108864 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -32520,10 +32703,24 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -32533,8 +32730,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } if (!message) { if (relation === comparableRelation) { @@ -33015,7 +33212,7 @@ var ts; } else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. + // A is the constraint of T. var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -33050,7 +33247,7 @@ var ts; } else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. + // A is the constraint of S. var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -33058,10 +33255,11 @@ var ts; return result; } } - else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. + else if (target.flags & 1048576 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -33195,6 +33393,9 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { @@ -33405,6 +33606,9 @@ var ts; var result = -1 /* True */; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -33574,7 +33778,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -33765,17 +33969,25 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } return result; } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -33801,7 +34013,7 @@ var ts; var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); return primaryTypes.length ? getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : - getUnionType(types, /*subtypeReduction*/ true); + getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -33867,8 +34079,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -34059,7 +34271,7 @@ var ts; // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). - return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -34146,6 +34358,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173 /* MappedType */: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -34201,6 +34416,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -34211,6 +34427,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -34237,7 +34454,7 @@ var ts; function isTypeParameterAtTopLevel(type, typeParameter) { return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - /** Create an object with properties named in the string literal type. Every property has type `{}` */ + /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { @@ -34246,7 +34463,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4 /* Property */, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -34262,42 +34479,45 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { + function inferTypeForHomomorphicMappedType(source, target) { + var key = source.id + "," + target.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target) { var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0 /* String */); - if (properties.length === 0 && !indexInfo) { + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var inference = createInferenceInfo(typeParameter); - var inferences = [inference]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 16777216 /* Optional */; - var members = ts.createSymbolTable(); + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var propType = getTypeOfSymbol(prop); - // If any property contains context sensitive functions that have been skipped, the source type - // is incomplete and we can't infer a meaningful input type. - if (propType.flags & 16777216 /* ContainsAnyFunctionType */) { + if (getTypeOfSymbol(prop).flags & 16777216 /* ContainsAnyFunctionType */) { return undefined; } - var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; - var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); - inferredProp.declarations = prop.declarations; - inferredProp.type = inferTargetType(propType); - members.set(prop.escapedName, inferredProp); - } - if (indexInfo) { - indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); - return inference.candidates ? getUnionType(inference.candidates, /*subtypeReduction*/ true) : emptyObjectType; } + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + } + function inferReverseMappedType(sourceType, target) { + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -34312,10 +34532,11 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { + function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -34384,25 +34605,27 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - // We give lowest priority to inferences of implicitNeverType (which is used as the - // element type for empty array literals). Thus, inferences from empty array literals - // only matter when no other inferences are made. - var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; @@ -34418,15 +34641,15 @@ var ts; } } else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -34452,7 +34675,7 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2 /* NakedTypeVariable */; + priority |= 1 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -34496,9 +34719,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -34531,16 +34754,10 @@ var ts; // such that direct inferences to T get priority over inferences to Partial, for example. var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); - if (ts.contains(mappedTypeStack, key)) { - return; - } - (mappedTypeStack || (mappedTypeStack = [])).push(key); - var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); - mappedTypeStack.pop(); + var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4 /* MappedType */; + priority |= 2 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -34586,8 +34803,10 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromContravariantTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); @@ -34614,8 +34833,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -34647,7 +34866,7 @@ var ts; if (candidates.length > 1) { var objectLiterals = ts.filter(candidates, isObjectLiteralType); if (objectLiterals.length) { - var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true)); + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); } } @@ -34672,10 +34891,19 @@ var ts; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : - context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -34724,7 +34952,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -34919,8 +35148,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -34986,16 +35215,6 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576 /* 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) { @@ -35032,7 +35251,7 @@ var ts; parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -35071,7 +35290,7 @@ var ts; var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -35190,15 +35409,15 @@ var ts; // Apply a mapping function to a type and return the resulting type. If the source type // is a union type, the mapping function is applied to each constituent type and a union // of the resulting types is returned. - function mapType(type, mapper) { + function mapType(type, mapper, noReductions) { if (!(type.flags & 131072 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35212,7 +35431,7 @@ var ts; } } } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -35263,7 +35482,7 @@ var ts; return elementType.flags & 16384 /* Never */ ? autoArrayType : createArrayType(elementType.flags & 131072 /* Union */ ? - getUnionType(elementType.types, /*subtypeReduction*/ true) : + getUnionType(elementType.types, 2 /* Subtype */) : elementType); } // We perform subtype reduction upon obtaining the final array type from an evolving array type. @@ -35278,8 +35497,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 16384 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35325,10 +35544,7 @@ var ts; var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } + return apparentType !== unknownType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); } } return false; @@ -35578,7 +35794,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at @@ -35606,7 +35822,7 @@ var ts; // path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -35626,7 +35842,7 @@ var ts; firstAntecedentType = flowType; } var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis + // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. var cached_1 = cache.get(key); @@ -35649,7 +35865,7 @@ var ts; } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } @@ -35680,6 +35896,23 @@ var ts; } return type; } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (131072 /* Union */ | 65536 /* Object */)) || (type.flags & 32768 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { case 58 /* EqualsToken */: @@ -35691,10 +35924,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && (right_1.kind === 9 /* StringLiteral */ || right_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && (left_1.kind === 9 /* StringLiteral */ || left_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -35715,6 +35948,12 @@ var ts; break; case 93 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); + case 92 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if ((expr.left.kind === 9 /* StringLiteral */ || expr.left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; case 26 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } @@ -35799,7 +36038,7 @@ var ts; var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -35879,7 +36118,7 @@ var ts; return type; } var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; + var predicate = getTypePredicateOfSignature(signature); if (!predicate) { return type; } @@ -36013,22 +36252,28 @@ var ts; var parent = node.parent; return parent.kind === 180 /* PropertyAccessExpression */ || parent.kind === 182 /* CallExpression */ && parent.expression === node || - parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 204 /* NonNullExpression */ || + parent.kind === 177 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getDeclaredOrApparentType(symbol, node) { + function getApparentTypeForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - var type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } return type; } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36054,9 +36299,9 @@ var ts; return getTypeOfSymbol(symbol); } // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. - if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; @@ -36097,7 +36342,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -36133,6 +36378,7 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -36144,7 +36390,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || node.parent.kind === 204 /* NonNullExpression */ || @@ -36346,6 +36592,15 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. @@ -36380,11 +36635,6 @@ var ts; return type; } } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -36659,7 +36909,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -36680,7 +36930,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. indexOfParameter -= 1; @@ -36708,7 +36958,7 @@ var ts; // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer || node.kind === 58 /* EqualsToken */) { + if (ts.hasInitializer(declaration) && node === declaration.initializer) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -36797,7 +37047,7 @@ var ts; // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. @@ -36826,12 +37076,6 @@ var ts; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - // For completions after `x === ` - return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; default: return undefined; } @@ -36860,10 +37104,10 @@ var ts; return mapType(type, function (t) { var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; - }); + }, /*noReductions*/ true); } function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { @@ -37032,12 +37276,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 198 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 183 /* NewExpression */: - if (node.kind === 94 /* NewKeyword */) { - return getContextualType(parent); - } - // falls through case 182 /* CallExpression */: + case 183 /* NewExpression */: return getContextualTypeForArgument(parent, node); case 185 /* TypeAssertionExpression */: case 203 /* AsExpression */: @@ -37072,12 +37312,6 @@ var ts; case 252 /* JsxOpeningElement */: case 251 /* JsxSelfClosingElement */: return getAttributesTypeFromJsxOpeningLikeElement(parent); - case 261 /* CaseClause */: { - if (node.kind === 73 /* CaseKeyword */) { - var switchStatement = parent.parent.parent; - return getTypeOfExpression(switchStatement.expression); - } - } } return undefined; } @@ -37088,7 +37322,7 @@ var ts; // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + var signatures = getSignaturesOfType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -37141,8 +37375,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -37163,8 +37397,6 @@ var ts; var result; if (signatureList) { result = cloneSignature(signatureList[0]); - // Clear resolved return type we possibly got from cloneSignature - result.resolvedReturnType = undefined; result.unionSignatures = signatureList; } return result; @@ -37238,7 +37470,7 @@ var ts; if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -37248,7 +37480,7 @@ var ts; } } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : + getUnionType(elementTypes, 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { @@ -37320,7 +37552,7 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, checkMode) { @@ -37330,7 +37562,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 0; + var propagatedFlags = 2097152 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 175 /* ObjectBindingPattern */ || contextualType.pattern.kind === 179 /* ObjectLiteralExpression */); @@ -37499,13 +37731,13 @@ var ts; type.flags & 65536 /* Object */ && !isGenericMappedType(type) || type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node); + function checkJsxSelfClosingElement(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); return getJsxGlobalElementType() || anyType; } - function checkJsxElement(node) { + function checkJsxElement(node, checkMode) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -37515,8 +37747,8 @@ var ts; } return getJsxGlobalElementType() || anyType; } - function checkJsxFragment(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + function checkJsxFragment(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); } @@ -37544,6 +37776,11 @@ var ts; ts.Debug.fail(); } } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } /** * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. * @@ -37553,11 +37790,10 @@ var ts; * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, * which also calls getSpreadType. */ - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); var spread = emptyObjectType; - var attributesArray = []; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; @@ -37566,9 +37802,7 @@ var ts; var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; // is sugar for + var exprType = checkJsxAttribute(attributeDecl, checkMode); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -37578,24 +37812,22 @@ var ts; attributeSymbol.type = exprType; attributeSymbol.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); - attributesArray.push(attributeSymbol); if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } } else { ts.Debug.assert(attributeDecl.kind === 259 /* JsxSpreadAttribute */); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - attributesArray = []; + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpression(attributeDecl.expression); + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 67108864 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -37603,18 +37835,8 @@ var ts; } } if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createSymbolTable(); - for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { - var attr = attributesArray_1[_b]; - if (!filter || filter(attr)) { - attributesTable.set(attr.escapedName, attr); - } + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864 /* JsxAttributes */); } } // Handle children attribute @@ -37629,27 +37851,27 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + createArrayType(getUnionType(childrenTypes)); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, 67108864 /* JsxAttributes */); } } if (hasSpreadAnyType) { return anyType; } - var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); - return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : - typeToIntersect ? typeToIntersect : attributeType; + return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ - function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + function createJsxAttributesType() { + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); result.flags |= 67108864 /* JsxAttributes */ | 8388608 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; @@ -37678,7 +37900,7 @@ var ts; * @param node a JSXAttributes to be resolved of its type */ function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } function getJsxType(name) { var jsxType = jsxTypes.get(name); @@ -37730,7 +37952,7 @@ var ts; * element is not a class element, or the class element type cannot be determined, returns 'undefined'. * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ - function getJsxElementInstanceType(node, valueType) { + function getJsxElementInstanceType(node, valueType, sourceAttributesType) { ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' @@ -37747,19 +37969,27 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0, isJavascript); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + } + else { + // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37927,19 +38157,19 @@ var ts; * * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature + * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) * @return attributes type if able to resolve the type of node * anyType if there is no type ElementAttributesProperty or there is an error * emptyObjectType if there is no "prop" in the element instance type */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), /*subtypeReduction*/ true); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + }), 2 /* Subtype */); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type if (elementType.flags & 2 /* String */) { @@ -37967,7 +38197,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -37977,7 +38207,7 @@ var ts; return statelessAttributesType; } // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { + if (elementClassType && sourceAttributesType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } if (isTypeAny(elemInstanceType)) { @@ -38053,14 +38283,20 @@ var ts; * @param node a custom JSX opening-like element * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { + if (!sourceAttributesType) { + // This ensures we cache non-inference uses of this calculation (ie, contextual types or services) + var links = getNodeLinks(node); + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { + var elemClassType = getJsxGlobalElementClassType(); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); + } + return links[linkLocation]; + } + else { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } - return links[linkLocation]; } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -38074,7 +38310,7 @@ var ts; else { // Because in language service, the given JSX opening-like element may be incomplete and therefore, // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ true); } } /** @@ -38087,7 +38323,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ false); } } /** @@ -38139,7 +38375,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node) { + function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -38161,7 +38397,7 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node); + checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); } else { checkJsxChildren(node.parent); @@ -38207,22 +38443,20 @@ var ts; * Check assignablity between given attributes property, "source attributes", and the "target attributes" * @param openingLikeElement an opening-like JSX element to check its JSXAttributes */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { // The function involves following steps: // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); - }); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); + // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, /*shouldIncludeAllStatelessAttributesType*/ false); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { @@ -38232,12 +38466,17 @@ var ts; // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; - if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); + if (!ts.isJsxAttribute(attribute)) { + continue; + } + var attrName = attribute.name; + var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); // We break here so that errors won't be cascading break; } @@ -38367,16 +38606,16 @@ var ts; return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } @@ -38390,15 +38629,20 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var propType; - var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; var apparentType = getApparentType(getWidenedType(leftType)); if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } return apparentType; } var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { @@ -38415,12 +38659,6 @@ var ts; else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); - // Reset the referenced-ness of the LHS expression if this access refers to a const enum or const enum only module - leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && - !(isNonLocalAlias(leftSymbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { - getSymbolLinks(leftSymbol).referenced = undefined; - } getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); if (assignmentKind) { @@ -38429,7 +38667,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -38496,6 +38734,9 @@ var ts; * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. */ function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } var classType = getTypeOfSymbol(prop.parent); while (true) { classType = getSuperClass(classType); @@ -38542,7 +38783,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -38647,32 +38888,43 @@ var ts; return res > max ? undefined : res; } 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; - } - else { - prop.isReferenced = true; + if (!prop || !noUnusedIdentifiers || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + 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; + } + else { + prop.isReferenced = true; + } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 180 /* PropertyAccessExpression */ - ? node.expression - : node.left; + var left = node.kind === 180 /* PropertyAccessExpression */ ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, type) { + var propType = getTypeOfFuncClassEnumModule(method); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var thisType = getThisTypeOfSignature(sig); + return !thisType || isTypeAssignableTo(type, thisType); + }); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(type, propertyName); @@ -38977,10 +39229,15 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } + function inferJsxTypeArguments(signature, sourceAttributesType, context) { + var paramType = getTypeAtPosition(signature, 0); + inferTypes(context.inferences, sourceAttributesType, paramType); + return getInferredTypes(context); + } function inferTypeArguments(node, signature, args, excludeArgument, context) { // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { @@ -39017,7 +39274,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -39073,7 +39330,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -39682,7 +39939,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { excludeArgument = undefined; @@ -39721,7 +39978,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -39755,7 +40012,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); } return resolveErrorCall(node); } @@ -39836,7 +40093,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -39876,6 +40133,26 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 /* Call */ + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -39889,7 +40166,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -39937,6 +40214,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -39981,8 +40259,8 @@ var ts; if (elementType.flags & 131072 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -40166,16 +40444,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default" /* Default */)) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); newSymbol.target = resolveSymbol(symbol); @@ -40183,7 +40463,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -40265,7 +40545,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks) { var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { + if (declaration && ts.hasInitializer(declaration)) { return getOptionalType(type); } } @@ -40374,7 +40654,6 @@ var ts; return promiseType; } function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } @@ -40391,9 +40670,9 @@ var ts; } } else { - var types = void 0; + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (functionFlags & 1 /* Generator */) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 /* Async */ ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function @@ -40405,7 +40684,6 @@ var ts; } } else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) { // For an async function, the return type will not be never, but rather a Promise for never. return functionFlags & 2 /* Async */ @@ -40420,8 +40698,9 @@ var ts; } } // Return a union of the return expression types. - type = getUnionType(types, /*subtypeReduction*/ true); + type = getUnionType(types, 2 /* Subtype */); } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!contextualSignature) { reportErrorsFromWidening(func, type); } @@ -40503,6 +40782,7 @@ var ts; } return true; } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -40528,8 +40808,7 @@ var ts; hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */)) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -40537,6 +40816,17 @@ var ts; } return aggregatedTypes; } + function mayReturnNever(func) { + switch (func.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + return true; + case 152 /* MethodDeclaration */: + return func.parent.kind === 179 /* ObjectLiteralExpression */; + default: + return false; + } + } /** * TypeScript Specification 1.0 (6.3) - July 2014 * An explicitly typed function whose return type isn't the Void type, @@ -40838,8 +41128,8 @@ var ts; } if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40914,6 +41204,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -41254,7 +41547,7 @@ var ts; leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: checkAssignmentOperator(rightType); @@ -41390,7 +41683,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getUnionType([type1, type2], /*subtypeReduction*/ true); + return getUnionType([type1, type2], 2 /* Subtype */); } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -41409,7 +41702,7 @@ var ts; node.contextualType = contextualType; node.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : - contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; var result = checkExpression(node, checkMode); node.contextualType = saveContextualType; node.contextualMapper = saveContextualMapper; @@ -41418,6 +41711,9 @@ var ts; function checkExpressionCached(node, checkMode) { var links = getNodeLinks(node); if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } // When computing a type that we're going to cache, we need to ignore any ongoing control flow // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart // to the top of the stack ensures all transient types are computed from a known point. @@ -41440,12 +41736,12 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 131072 /* Union */ && !(contextualType.flags & 8 /* Boolean */)) { + if (contextualType.flags & 393216 /* UnionOrIntersection */ && !(contextualType.flags & 8 /* Boolean */)) { // If the contextual type is a union containing both of the 'true' and 'false' types we // don't consider it a literal context for boolean literals. - var types_19 = contextualType.types; - return ts.some(types_19, function (t) { - return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_19, trueType) && containsType(types_19, falseType)) && + var types_18 = contextualType.types; + return ts.some(types_18, function (t) { + return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_18, trueType) && containsType(types_18, falseType)) && isLiteralOfContextualType(candidateType, t); }); } @@ -41571,9 +41867,10 @@ var ts; // - target in rhs of import statement var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -41665,11 +41962,11 @@ var ts; case 260 /* JsxExpression */: return checkJsxExpression(node, checkMode); case 250 /* JsxElement */: - return checkJsxElement(node); + return checkJsxElement(node, checkMode); case 251 /* JsxSelfClosingElement */: - return checkJsxSelfClosingElement(node); + return checkJsxSelfClosingElement(node, checkMode); case 254 /* JsxFragment */: - return checkJsxFragment(node); + return checkJsxFragment(node, checkMode); case 258 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); case 252 /* JsxOpeningElement */: @@ -41718,7 +42015,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { @@ -41749,7 +42046,7 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); if (!typePredicate) { return; } @@ -41764,7 +42061,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } @@ -42095,22 +42392,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && @@ -42326,6 +42607,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -42693,7 +42977,7 @@ var ts; } return undefined; } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); } /** * Gets the "awaited type" of a type. @@ -42726,7 +43010,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -42926,7 +43210,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -43283,22 +43567,35 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 152 /* MethodDeclaration */ || member.kind === 150 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; } - } - else if (member.kind === 153 /* Constructor */) { + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } - } + break; + case 158 /* IndexSignature */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } @@ -43615,7 +43912,9 @@ var ts; // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); - checkSourceElement(node.type); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } // JSDoc `function(string, string): string` syntax results in parameters with no name if (!node.name) { return; @@ -43664,13 +43963,19 @@ var ts; if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + } checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -43865,7 +44170,7 @@ var ts; // Grammar checking checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 + // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, @@ -43954,7 +44259,7 @@ var ts; var arrayTypes = inputType.types; var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } else if (arrayType.flags & 524322 /* StringLike */) { @@ -43999,7 +44304,7 @@ var ts; if (arrayElementType.flags & 524322 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); } return arrayElementType; } @@ -44086,7 +44391,7 @@ var ts; } return undefined; } - var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); if (checkAssignability && errorNode && iteratedType) { // If `checkAssignability` was specified, we were called from @@ -44154,7 +44459,7 @@ var ts; } return undefined; } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); if (isTypeAny(nextResult)) { return undefined; } @@ -44209,56 +44514,56 @@ var ts; } function checkReturnStatement(node) { // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } + if (checkGrammarStatementInAmbientContext(node)) { + return; } var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // A generator does not need its return expressions checked against its return type. // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added + // TODO: Check return types of generators when return type tracking is added // for generators. return; } - if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 155 /* SetAccessor */) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } + else if (func.kind === 155 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 153 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } + } + else if (func.kind === 153 /* Constructor */) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - // If the function has a return type, but promisedType is - // undefined, an error will be reported in checkAsyncFunctionReturnType - // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2 /* Async */) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); } } + else { + checkTypeAssignableTo(exprType, returnType, node); + } } - else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - // The function has a return type, but the return statement doesn't have an expression. - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } + } + else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkWithStatement(node) { @@ -44420,7 +44725,8 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -44539,9 +44845,11 @@ var ts; // type parameter at this position, we report an error. var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } } // If the type parameter node has a default and it is not identical to the default // for the type parameter at this position, we report an error. @@ -44614,7 +44922,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -44644,7 +44955,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -44659,6 +44976,35 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { @@ -44962,6 +45308,7 @@ var ts; case 37 /* PlusToken */: return left + right; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; + case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } break; @@ -46186,6 +46533,7 @@ var ts; } return undefined; case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript @@ -46311,7 +46659,7 @@ var ts; // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -46358,35 +46706,28 @@ var ts; return ts.typeHasCallOrConstructSignatures(type, checker); } function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_4 = []; - var name_4 = symbol.escapedName; - ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_4); - if (symbol) { - symbols_4.push(symbol); - } - }); - return symbols_4; + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); } else if (symbol.flags & 33554432 /* Transient */) { - var transient = symbol; - if (transient.leftSpread) { - return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); - } - if (transient.syntheticOrigin) { - return getRootSymbols(transient.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; } - return [symbol]; + return target; } // Emitter support function isArgumentsLocalBinding(node) { @@ -46494,7 +46835,7 @@ var ts; // AND // - binding is not declared in loop, should be renamed to avoid name reuse across siblings // let a, b - // { let x = 1; a = () => x; } + // { let x = 1; a = () => x; } // { let x = 100; b = () => x; } // console.log(a()); // should print '1' // console.log(b()); // should print '100' @@ -46737,20 +47078,20 @@ var ts; : unknownType; if (type.flags & 1024 /* UniqueESSymbol */ && type.symbol === symbol) { - flags |= 131072 /* AllowUniqueESSymbolType */; + flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 8192 /* AddUndefined */) { + if (flags & 131072 /* AddUndefined */) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -47350,9 +47691,6 @@ var ts; } } function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } if (typeParameters && typeParameters.length === 0) { var start = typeParameters.pos - "<".length; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; @@ -47436,6 +47774,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -47896,12 +48241,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); @@ -48095,7 +48443,7 @@ var ts; if (node.flags & 2097152 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } @@ -48360,7 +48708,7 @@ var ts; var node = createSynthesizedNode(71 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; - node.autoGenerateKind = 0 /* None */; + node.autoGenerateFlags = 0 /* None */; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -48375,22 +48723,24 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - /** Create a unique temporary variable. */ - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateFlags = 1 /* Auto */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + } return name; } ts.createTempVariable = createTempVariable; /** Create a unique temporary variable for use in a loop. */ function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateFlags = 2 /* Loop */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -48399,7 +48749,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateFlags = 3 /* Unique */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -48407,10 +48757,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4 /* Node */; + name.autoGenerateFlags = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; + } nextAutoGenerateId++; return name; } @@ -48708,11 +49060,12 @@ var ts; } ts.updateIndexSignature = updateIndexSignature; /* @internal */ - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -51575,13 +51928,13 @@ var ts; if (isLeftSideOfBinary) { // No need to parenthesize the left operand when the binary operator is // left associative: - // (a*b)/x -> a*b/x - // (a**b)/x -> a**b/x + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x // // Parentheses are needed for the left operand when the binary operator is // right associative: - // (a/b)**x -> (a/b)**x - // (a**b)**x -> (a**b)**x + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x return binaryOperatorAssociativity === 1 /* Right */; } else { @@ -51681,7 +52034,9 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || + emittedExpression.kind === 293 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -52331,6 +52686,7 @@ var ts; /// var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -52465,7 +52821,7 @@ var ts; switch (kind) { // Names case 71 /* Identifier */: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145 /* ComputedPropertyName */: @@ -52612,7 +52968,7 @@ var ts; case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217 /* ForOfStatement */: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219 /* BreakStatement */: @@ -53436,6 +53792,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -53535,7 +53892,12 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { // If the right-hand value of the destructuring assignment needs to be preserved (as // is the case when the destructuring assignment is part of a larger expression), // then we need to cache the right-hand value. @@ -53579,6 +53941,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -53606,6 +53988,15 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -53994,7 +54385,7 @@ var ts; */ var classAliases; /** - * Keeps track of whether we are within any containing namespaces when performing + * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; @@ -54691,11 +55082,14 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. @@ -56864,7 +57258,7 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -56878,6 +57272,7 @@ var ts; * just-in-time substitution for `super` expressions inside of async methods. */ var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -56915,6 +57310,83 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 215 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 216 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 217 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 264 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 208 /* Block */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 221 /* WithStatement */: + case 223 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } /** * Visits an AwaitExpression node. * @@ -56989,6 +57461,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -57001,10 +57540,17 @@ var ts; // `this` and `arguments` objects to `__awaiter`. The generator function // passed to `__awaiter` is executed inside of the callback to the // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -57020,27 +57566,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -57304,7 +57851,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); @@ -57316,8 +57863,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -57818,7 +58365,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncIterator) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -59001,7 +59548,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -60185,7 +60732,7 @@ var ts; ])); } /** - * Visits an ObjectLiteralExpression with computed propety names. + * Visits an ObjectLiteralExpression with computed property names. * * @param node An ObjectLiteralExpression node. */ @@ -64101,8 +64648,8 @@ var ts; // `throw` methods that step through the generator when invoked. // // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. // // variables: // _ Persistent state for the generator that is shared between the helper and the @@ -64282,7 +64829,7 @@ var ts; // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: @@ -64307,6 +64854,8 @@ var ts; ]))) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Transforms a SourceFile into a UMD module. @@ -64357,7 +64906,7 @@ var ts; // define(["require", "exports"], factory); // } // })(function ...) - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: @@ -64375,6 +64924,8 @@ var ts; ])) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Collect the additional asynchronous dependencies for the module. @@ -64426,6 +64977,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } /** * Transforms a SourceFile into an AMD or UMD module body. * @@ -64440,6 +65002,9 @@ var ts; } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); // Append the 'export =' statement if provided. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); @@ -64611,7 +65176,12 @@ var ts; ts.setEmitFlags(func, 8 /* CapturesThis */); } } - return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") @@ -64621,6 +65191,10 @@ var ts; // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } var func; if (languageVersion >= 2 /* ES2015 */) { func = ts.createArrowFunction( @@ -64647,6 +65221,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } /** * Visits an ImportDeclaration node. * @@ -64665,7 +65253,7 @@ var ts; if (namespaceDeclaration && !ts.isDefaultImport(node)) { // import * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { // import d from "mod"; @@ -64673,7 +65261,7 @@ var ts; // import d, { x, y } from "mod"; // import d, * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node))); @@ -65406,6 +65994,18 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); /// /// @@ -65423,6 +66023,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. @@ -66656,6 +67257,43 @@ var ts; if (hint === 1 /* Expression */) { return substituteExpression(node); } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 266 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } return node; } /** @@ -66846,9 +67484,11 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration( + var tslibImport = ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67522,9 +68162,9 @@ var ts; * @param tokenStartPos The start pos of the token. * @param emitCallback The callback used to emit the token. */ - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -67533,7 +68173,7 @@ var ts; if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { @@ -67558,7 +68198,7 @@ var ts; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -68099,8 +68739,8 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { - // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { + // if file was external module this fact should be preserved in .d.ts as well. // in case if we didn't write any external module specifiers in .d.ts we need to emit something // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); @@ -68278,9 +68918,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 /* UseTypeOfFunction */ | - 16384 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -68294,7 +68934,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); errorNameNode = undefined; } } @@ -68532,12 +69172,15 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); write(";"); writeLine(); return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators + } if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -68625,6 +69268,7 @@ var ts; var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators write("export "); } if (modifiers & 512 /* Default */) { @@ -68766,6 +69410,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -69199,7 +69844,7 @@ var ts; // if this is property of type literal, // or is parameter of method/call/construct/index signature of type literal // emit only if type is specified - if (node.type) { + if (ts.hasType(node)) { write(": "); emitType(node.type); } @@ -69650,6 +70295,7 @@ var ts; // it allows emitSeparatedList to write separator appropriately) // Example: // original: function foo([, x, ,]) {} + // tslint:disable-next-line no-double-space // emit : function foo([ , x, , ]) {} write(" "); } @@ -69767,7 +70413,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -69798,7 +70444,6 @@ var ts; /// var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ /** @@ -69818,7 +70463,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -69827,7 +70475,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -69960,7 +70611,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -70026,16 +70677,29 @@ var ts; var generatedNames; // Set of names generated by the NameGenerator. var tempFlagsStack; // Stack of enclosing name generation scopes. var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { // public API printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, // internal API writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -70058,6 +70722,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -70073,6 +70741,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -70100,7 +70778,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -70126,6 +70804,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0 /* Auto */; + reservedNamesStack = []; comments.reset(); setWriter(/*output*/ undefined); } @@ -70189,7 +70868,9 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { @@ -70198,7 +70879,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -70436,7 +71117,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -70460,7 +71141,7 @@ var ts; case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: case 91 /* ImportKeyword */: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; // Expressions case 178 /* ArrayLiteralExpression */: @@ -70556,25 +71237,27 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); } } // // Identifiers // function emitIdentifier(node) { - write(getTextOfNode(node, /*includeTrivia*/ false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names // function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -70586,36 +71269,46 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } // // Signature elements // function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } // @@ -70624,19 +71317,19 @@ var ts; function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -70645,8 +71338,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -70658,13 +71351,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); + writeKeyword(node.kind === 154 /* GetAccessor */ ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -70673,34 +71367,37 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } // // Types // function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -70710,7 +71407,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -70732,34 +71431,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); @@ -70768,29 +71472,29 @@ var ts; emitList(node, node.types, 264 /* IntersectionTypeConstituents */); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -70798,23 +71502,24 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); @@ -70823,32 +71528,24 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); - write("}"); - } + writePunctuation("{"); + emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); - write("]"); - } + writePunctuation("["); + emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Expressions @@ -70885,7 +71582,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -70911,9 +71608,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -70921,26 +71618,27 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -70953,30 +71651,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -71000,7 +71702,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; @@ -71009,7 +71711,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -71037,12 +71739,12 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -71055,17 +71757,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } // @@ -71079,13 +71783,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; @@ -71094,27 +71798,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, node); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, node); + var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, node); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); + writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212 /* IfStatement */) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -71123,55 +71827,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -71185,58 +71897,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, /*contextNode*/ contextNode); + pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -71244,24 +71960,26 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos); - write(";"); + writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); + writeSemicolon(); } // // Declarations // function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { @@ -71270,9 +71988,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -71302,19 +72020,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: @@ -71347,7 +72065,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -71359,7 +72078,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, body); + writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -71384,17 +72103,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -71402,66 +72125,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* HeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* InterfaceMembers */); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81 /* EnumMembers */); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512 /* GlobalAugmentation */) { - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234 /* ModuleDeclaration */) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end); + writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71 /* Identifier */) { @@ -71473,23 +72207,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -71499,28 +72240,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -71529,14 +72286,16 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } @@ -71544,9 +72303,10 @@ var ts; // Module references // function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } // // JSX @@ -71557,14 +72317,14 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -71572,45 +72332,46 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -71625,13 +72386,15 @@ var ts; // Clauses // function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -71658,25 +72421,25 @@ var ts; } var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); - write(" "); + var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } @@ -71685,7 +72448,8 @@ var ts; // function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); // This is to ensure that we emit comment in the following case: // For example: // obj = { @@ -71703,13 +72467,15 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } @@ -71718,7 +72484,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Top-level nodes @@ -71816,33 +72582,60 @@ var ts; // // Helpers // + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328 /* Modifiers */); - write(" "); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } } - function emitNodeWithPrefix(prefix, node, emit) { + function emitWithLeadingSpace(node) { if (node) { - write(prefix); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { - write(" "); + writeSpace(); emit(node); } else { @@ -71856,13 +72649,16 @@ var ts; emitList(parentNode, decorators, 24577 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360 /* Parameters */); + emitList(parentNode, parameters, 1296 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -71882,7 +72678,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -71897,6 +72693,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -71915,7 +72728,7 @@ var ts; return; } if (format & 7680 /* BracketsMask */) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -71926,7 +72739,7 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { - write(" "); + writeSpace(); } } else { @@ -71938,7 +72751,7 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } // Increase the indent, if requested. if (format & 64 /* Indented */) { @@ -71947,7 +72760,6 @@ var ts; // Emit each child. var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -71958,10 +72770,10 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new @@ -71974,7 +72786,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { - write(" "); + writeSpace(); } } // Emit this child. @@ -71997,7 +72809,7 @@ var ts; // Write a trailing comma, if requested. var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { - write(","); + writePunctuation(","); } // Emit any trailing comment of the last element in the list // i.e @@ -72005,7 +72817,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -72017,50 +72829,102 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -72251,6 +73115,7 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } /** * Pop the current name generation scope. @@ -72260,15 +73125,22 @@ var ts; return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } /** * Generate the text for a generated identifier. */ function generateName(name) { - if (name.autoGenerateKind === 4 /* Node */) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.skipNameGenerationScope) { + if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { var savedTempFlags = tempFlags; popNameGenerationScope(/*node*/ undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -72298,7 +73170,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } /** * Returns a value indicating whether a name is unique within a container. @@ -72320,11 +73193,14 @@ var ts; * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. */ - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 /* _i */ ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -72337,6 +73213,9 @@ var ts; ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -72429,11 +73308,11 @@ var ts; * Generates a unique identifier for a node. */ function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); } @@ -72451,7 +73330,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateFlags === 4 /* Node */ && node.autoGenerateId !== autoGenerateId) { break; } @@ -72462,17 +73341,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0 /* None */] = ""; - delimiters[16 /* CommaDelimited */] = ","; - delimiters[4 /* BarDelimited */] = " |"; - delimiters[8 /* AmpersandDelimited */] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28 /* DelimitersMask */]; - } function createBracketsMap() { var brackets = []; brackets[512 /* Braces */] = ["{", "}"]; @@ -72494,474 +73362,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - // Line separators - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - // Delimiters - ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; - ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; - ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; - ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; - // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; - // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; - // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; - ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - 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 changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - 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); }, - // Remove existing file info - onDeleteValue: removeExistingFileInfo, - // We will update in place instead of deleting existing value and adding new one - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - 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); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - 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); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - 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)]; - } - var seenFiles = ts.createMap(); - 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)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - 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]; - 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(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * @return {boolean} indicates if the shape signature has changed since last update. - */ - 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 = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Gets all files of the program excluding the default library file - */ - 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) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - 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 [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - // Changed if we had references - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - // If there are any new references that werent present previously there is change - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - // Otherwise its changed if there are more references previously than now - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - // Remove existing references - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - // add files referencing the removedFilePath, as changed files too - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - // Delete the entry for the removed file path - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.mapDefinedIter(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - }); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - 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(); - // Start with the paths this file was referenced by - var path = sourceFile.path; - 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); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - // Return array of values that needs emit - return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); /// /// /// -/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; @@ -73155,23 +73559,31 @@ var ts; return errorMessage; } ts.formatDiagnostic = formatDiagnostic; - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } - function formatAndReset(text, formatStyle) { + /** @internal */ + function formatColorAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } + ts.formatColorAndReset = formatColorAndReset; function padLeft(s, length) { while (s.length < length) { s = " " + s; @@ -73184,9 +73596,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -73199,7 +73611,7 @@ var ts; // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -73208,11 +73620,11 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += redForegroundEscapeSequence; + context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += ForegroundColorEscapeSequences.Red; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. @@ -73229,19 +73641,25 @@ var ts; } context += resetEscapeSequence; } - output += host.getNewLine(); - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + output += " - "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); output += context; } output += host.getNewLine(); } - return output; + return output + host.getNewLine(); } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { @@ -73509,7 +73927,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -73656,9 +74075,13 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); - if (resolutionToFile) { - // module used to be resolved to file - ignore it + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. return false; } var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); @@ -73811,7 +74234,7 @@ var ts; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); @@ -73915,24 +74338,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } // Create the emit resolver outside of the "emitTime" tracking code below. That way @@ -73943,7 +74368,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -74306,6 +74731,7 @@ var ts; // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -74495,7 +74921,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -74622,7 +75048,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { @@ -74796,217 +75222,2408 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { - // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + if (ts.isArrayLiteralExpression(keyProps.initializer) && + keyProps.initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionPathsSyntax() { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + } + return ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile && options.configFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || + !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function checkAllDefined(names) { + ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); + return names; + } + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + 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 (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.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 (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // 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(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + if (map1 === undefined) { + return map2 === undefined; + } + if (map2 === undefined) { + return map1 === undefined; + } + // Has same size and every key is present in both maps + return map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState && oldState.referencedMap; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.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 = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var host; + var newProgram; + if (ts.isArray(newProgramOrRootNames)) { + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program) { + newProgram = undefined; + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = void 0; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * 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, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + function addFileWatcher(host, file, cb) { + return host.watchFile(file, cb); + } + ts.addFileWatcher = addFileWatcher; + function addFileWatcherWithLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb); + } + ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; + function addFilePathWatcher(host, file, cb, path) { + return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); + } + ts.addFilePathWatcher = addFilePathWatcher; + function addFilePathWatcherWithLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb, path); + } + ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; + function addDirectoryWatcher(host, directory, cb, flags) { + var recursive = (flags & 1 /* Recursive */) !== 0; + return host.watchDirectory(directory, cb, recursive); + } + ts.addDirectoryWatcher = addDirectoryWatcher; + function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { + var info = "PathInfo: " + file; + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } + var watcher = addWatch(host, file, function (fileName, cbOptional1) { + var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; + log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); + var start = ts.timestamp(); + cb(fileName, cbOptional1, optional); + var elapsed = ts.timestamp() - start; + log(watcherCaption + "Elapsed: " + elapsed + "ms Trigger: " + fileName + optionalInfo + " " + info); + }, optional); + return { + close: function () { + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } + watcher.close(); + } + }; + } + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var allFilesHaveInvalidatedResolution = false; + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = rootDir && resolutionHost.toPath(rootDir); + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return collected && collected.has(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + clearPerDirectoryResolutions(); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + if (resolution.failedLookupLocations) { + if (existingResolution && existingResolution.failedLookupLocations) { + watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution); + } + else { + watchFailedLookupLocationOfResolution(resolution, 0); + } + } + else if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + 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 }; + } + var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); + var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch + if (isNodeModulesDirectory(dirPath)) { + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + } + // Use some ancestor of the root directory + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) { + var failedLookupLocations = resolution.failedLookupLocations; + var existingFailedLookupLocations = existingResolution.failedLookupLocations; + for (var index = 0; index < failedLookupLocations.length; index++) { + if (index === existingFailedLookupLocations.length) { + // Additional failed lookup locations, watch from this index + watchFailedLookupLocationOfResolution(resolution, index); + return; + } + else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) { + // Different failed lookup locations, + // Watch new resolution failed lookup locations from this index and + // stop watching existing resolutions from this index + watchFailedLookupLocationOfResolution(resolution, index); + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index); + return; + } + } + // All new failed lookup locations are already watched (and are same), + // Stop watching failed lookup locations of existing resolution after failed lookup locations length + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length); + } + function watchFailedLookupLocationOfResolution(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, 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 }); + } + } + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (resolution.failedLookupLocations) { + stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0); + } + } + function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + 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) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // If the files are added to project root or node_modules directory, always run through the invalidation process + // Otherwise run through invalidation only if adding to the immediate directory + if (!allFilesHaveInvalidatedResolution && + dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + } + }, 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } - // Cannot specify module gen that isn't amd or system with --out - if (outFile) { - if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + else { + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } } - // there has to be common source directory if user specified --outdir || --sourceRoot - // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted - if (options.outDir || // there is --outDir specified - options.sourceRoot || // there is --sourceRoot specified - options.mapRoot) { - // Precalculate and cache the common source directory - var dir = getCommonSourceDirectory(); - // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure - if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function createTypeRootsWatch(_typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // 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, + onDeleteValue: ts.closeFileWatcher + }); } - if (options.checkJs && !options.allowJs) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + else { + closeTypeRootsWatch(); } - if (options.emitDecoratorMetadata && - !options.experimentalDecorators) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + /** + * 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 = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { + if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + system.clearScreen(); + } + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onConfigFileDiagnostic = undefined; + host.onUnRecoverableConfigFileDiagnostic = undefined; + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + var cwd = host.getCurrentDirectory(); + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + return configParseResult; + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + // First get and report any syntactic errors. + var diagnostics = program.getSyntacticDiagnostics().slice(); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === 0) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); } - if (options.jsxFactory) { - if (options.reactNamespace) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); - } - if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; } + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + var _a; + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; + var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onConfigFileDiagnostic: host.onConfigFileDiagnostic, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + if (configFileName && !rootFileNames) { + parseConfigFile(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + var writeLog = loggingEnabled ? trace : ts.noop; + var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; + var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; + var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, writeLog); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var newLine = updateNewLine(); + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: watchDirectory, + watchTypeRootsDirectory: watchDirectory, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : + (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : + (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + return builderProgram; + } + // Compile the program + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); + return builderProgram; + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function fileExists(fileName) { + var path = toPath(fileName); + var hostSourceFileInfo = sourceFilesCache.get(path); + if (hostSourceFileInfo !== undefined) { + return !ts.isString(hostSourceFileInfo); } - else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); - } - // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files - if (!options.noEmit && !options.suppressOutputPathCheck) { - var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createMap(); - ts.forEachEmittedFile(emitHost, function (emitFileNames) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); - verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); - }); + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (ts.isString(hostSourceFile)) { + return undefined; } - // Verify that all the emit files are unique and don't overwrite input files - function verifyEmitFilePath(emitFileName, emitFilesSeen) { - if (emitFileName) { - var emitFilePath = toPath(emitFileName); - // Report error if the output overwrites input file - if (filesByName.has(emitFilePath)) { - var chain_1; - if (!options.configFilePath) { - // The program is from either an inferred project or an external project - chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } - var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; - // Report error if multiple files write into same file - if (emitFilesSeen.has(emitFileKey)) { - // Already seen the same emit file - report error - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + else { + // There is no source file on host any more, close the watch, missing file paths will track it + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, hostSourceFile.version.toString()); + } + } + else { + var fileWatcher = void 0; + if (sourceFile) { + sourceFile.version = "1"; + fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: 1, fileWatcher: fileWatcher }); } else { - emitFilesSeen.set(emitFileKey, true); + sourceFilesCache.set(path, "0"); } } + return sourceFile; } - } - function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { - var pathProp = pathsSyntax_1[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer)) { - for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { - var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); - needCompilerDiagnostic = false; - } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); } } - } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; } } - function createDiagnosticForOptionPaths(onKey, key, message, arg0) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { - var pathProp = pathsSyntax_2[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer) && - createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { - needCompilerDiagnostic = false; + function removeSourceFile(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + resolutionCache.invalidateResolutionOfFile(path); } + sourceFilesCache.delete(path); } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || ts.isString(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (ts.isString(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + sourceFilesCache.delete(oldSourceFile.path); + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } - function getOptionPathsSyntax() { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); } - return ts.emptyArray; } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + timerToUpdateProgram = host.setTimeout(updateProgram, 250); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; } } - function getCompilerOptionsObjectLiteralSyntax() { - if (_compilerOptionsObjectLiteralSyntax === undefined) { - _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isObjectLiteralExpression(prop.initializer)) { - _compilerOptionsObjectLiteralSyntax = prop.initializer; - break; - } + function reloadFileNamesFromConfigFile() { + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { + host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + var configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); + rootFileNames = configParseResult.fileNames; + compilerOptions = configParseResult.options; + configFileSpecs = configParseResult.configFileSpecs; + configFileWildCardDirectories = configParseResult.wildcardDirectories; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile) { + // Update the cache + if (eventKind === ts.FileWatcherEventKind.Deleted) { + resolutionCache.invalidateResolutionOfFile(path); + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, (++hostSourceFile.version).toString()); + } + } + else { + // Deleted file created + if (ts.isString(hostSourceFile)) { + sourceFilesCache.delete(path); + } + else { + // file changed - just update the version + hostSourceFile.version++; } } } - return _compilerOptionsObjectLiteralSyntax; + // Update the program + scheduleProgramUpdate(); } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { - var props = ts.getPropertyAssignment(objectLiteral, key1, key2); - for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { - var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); } - return !!props.length; } - function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); - programDiagnostics.add(diag); + function watchDirectory(directory, cb, flags) { + return watchDirectoryWorker(host, directory, cb, flags, writeLog); } - } - ts.createProgram = createProgram; - /* @internal */ - /** - * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. - * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. - * This returns a diagnostic even if the module will be an untyped module. - */ - function getResolutionDiagnostic(options, _a) { - var extension = _a.extension; - switch (extension) { - case ".ts" /* Ts */: - case ".d.ts" /* Dts */: - // These are always allowed. - return undefined; - case ".tsx" /* Tsx */: - return needJsx(); - case ".jsx" /* Jsx */: - return needJsx() || needAllowJs(); - case ".js" /* Js */: - return needAllowJs(); + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); } - function needJsx() { - return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + removeSourceFile(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } } - function needAllowJs() { - return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + function watchConfigFileWildCardDirectories() { + if (configFileWildCardDirectories) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } } - } - ts.getResolutionDiagnostic = getResolutionDiagnostic; - function checkAllDefined(names) { - ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); - return names; - } - function getModuleNames(_a) { - var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; - var res = imports.map(function (i) { return i.text; }); - for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { - var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { - res.push(aug.text); + function watchWildcardDirectory(directory, flags) { + return watchDirectory(directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + var result = cachedDirectoryStructureHost && cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + // Instead of deleting the file, mark it as changed instead + // Many times node calls add/remove/file when watching directories recursively + var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); + if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { + hostSourceFile.version++; + } + else { + removeSourceFile(fileOrDirectoryPath); + } + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } } - // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. } - return res; } + ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); /// /// @@ -75153,12 +77770,14 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", + "esnext.promise": "lib.esnext.promise.d.ts", }), }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -75406,6 +78025,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -75696,19 +78322,19 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - var result = { + return { enable: typeAcquisition.enableAutoDiscovery, include: typeAcquisition.include || [], exclude: typeAcquisition.exclude || [] }; - return result; } return typeAcquisition; } @@ -76171,7 +78797,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean @@ -76200,7 +78826,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } @@ -76616,8 +79242,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - return options; + return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -76709,20 +79334,6 @@ var ts; * \/?$ # matches an optional trailing directory separator at the end of the string. */ var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - /** - * Tests for a path with multiple recursive directory wildcards. - * Matches **\** and **\a\**, but not **\a**b. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. - * (.*\/)? # optionally matches any number of characters followed by a directory separator. - * \*\* # matches a recursive directory wildcard "**" - * ($|\/) # matches either the end of the string or a directory separator. - */ - var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; /** * Tests for a path where .. appears after a recursive directory wildcard. * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* @@ -76891,9 +79502,6 @@ var ts; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } - else if (invalidMultipleRecursionPatterns.test(spec)) { - return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; - } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } @@ -77235,6 +79843,7 @@ var ts; ScriptElementKindModifier["ambientModifier"] = "declare"; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -77754,7 +80363,7 @@ var ts; return isCompletedNode(n.thenStatement, sourceFile); case 211 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25 /* SemicolonToken */); + hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); case 178 /* ArrayLiteralExpression */: case 176 /* ArrayBindingPattern */: case 181 /* ElementAccessExpression */: @@ -77777,11 +80386,9 @@ var ts; return isCompletedNode(n.statement, sourceFile); case 213 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - var hasWhileKeyword = findChildOfKind(n, 106 /* WhileKeyword */, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); + return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) + : isCompletedNode(n.statement, sourceFile); case 163 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); case 190 /* TypeOfExpression */: @@ -77811,7 +80418,6 @@ var ts; return true; } } - ts.isCompletedNode = isCompletedNode; /* * Checks if node ends with 'expectedLastToken'. * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. @@ -77851,7 +80457,7 @@ var ts; } ts.hasChildOfKind = hasChildOfKind; function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); } ts.findChildOfKind = findChildOfKind; function findContainingList(node) { @@ -78042,8 +80648,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -78260,12 +80866,16 @@ var ts; ts.typeKeywords = [ 119 /* AnyKeyword */, 122 /* BooleanKeyword */, + 127 /* KeyOfKeyword */, 130 /* NeverKeyword */, + 95 /* NullKeyword */, 133 /* NumberKeyword */, 134 /* ObjectKeyword */, 136 /* StringKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, + 139 /* UndefinedKeyword */, + 140 /* UniqueKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -78286,6 +80896,28 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; + /** Add a value to a set, and return true if it wasn't already present. */ + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -78300,6 +80932,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -78309,8 +80942,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -78431,14 +81074,17 @@ var ts; /** * The default is CRLF. */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; + /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -78451,35 +81097,23 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { - return ts.getTextOfIdentifierOrLiteral(location); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && @@ -78493,12 +81127,16 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -78525,57 +81163,6 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; - function getOpenBrace(constructor, sourceFile) { - // First token is the open curly, this is where we want to put the 'super' call. - return constructor.body.getFirstToken(sourceFile); - } - ts.getOpenBrace = getOpenBrace; - function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); - } - ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; - function getSourceFileImportLocation(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); - var position = 0; - if (shebang !== undefined) { - position = shebang.length; - advancePastLineBreak(); - } - // For a source file, it is possible there are detached comments we should not skip - var ranges = ts.getLeadingCommentRanges(text, position); - if (!ranges) - return position; - // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end; - advancePastLineBreak(); - ranges = ranges.slice(1); - } - // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { - position = range.end; - advancePastLineBreak(); - continue; - } - break; - } - return position; - function advancePastLineBreak() { - if (position < text.length) { - var charCode = text.charCodeAt(position); - if (ts.isLineBreak(charCode)) { - position++; - if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { - position++; - } - } - } - } - } - ts.getSourceFileImportLocation = getSourceFileImportLocation; /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -78607,6 +81194,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ @@ -78880,7 +81471,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -78889,8 +81480,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -79213,32 +81804,39 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. continue; - } - // for the ||||||| and ======== markers, add a comment for the first line, - // and then lex all subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); } } } @@ -79400,7 +81998,7 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } - // Special case < and > If they appear in a generic context they are punctuation, + // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then @@ -79510,11 +82108,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -79594,7 +82192,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -79629,37 +82227,20 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; + for (var path in paths) { var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); } } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } - } - }; - for (var path in paths) { - _loop_6(path); } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -79671,50 +82252,60 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - if (matches) { - var result = []; - // Trim away prefix and suffix - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + if (!host.readDirectory) { + return undefined; } - return undefined; + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + var directories = tryGetDirectories(host, baseDirectory); + // Trim away prefix and suffix + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module @@ -79786,10 +82377,12 @@ var ts; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -79801,31 +82394,38 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -79963,26 +82563,55 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } + if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) + && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { + return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); 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, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { + switch (completionData.kind) { + case 0 /* Data */: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1 /* JsDocTagName */: + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2 /* JsDocTag */: + // If the current position is a jsDoc tag, only tags should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3 /* JsDocParameterName */: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
completion list at "1" will contain "div" with type any + // var x =
+ // The completion list at "1" will contain "div" with type any var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -79992,37 +82621,37 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - // If the current position is a jsDoc tag name, only tag names should be provided for completion - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - // If the current position is a jsDoc tag, only tags should be provided for completion - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, 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, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if // - this is not a member completion list (all the keywords) // - other filters are enabled in required scenario so add those keywords + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -80030,14 +82659,9 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: "1" @@ -80045,12 +82669,30 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (includeInsertTextCompletions) { + if (origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + // TODO: GH#20619 Use configured quote style + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + } + } + if (insertText !== undefined && !includeInsertTextCompletions) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -80061,13 +82703,15 @@ var ts; // Use a 'sortText' of 0' so that all symbol completion entries come before any other // entries (like JavaScript identifier entries). return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -80078,103 +82722,119 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); - if (symbols) { - for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { - var symbol = symbols_5[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); - if (!entry) { - continue; - } - var name = entry.name; - if (uniques.has(name)) { - continue; - } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { - uniques.set(name, true); - } - entries.push(entry); + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); } + entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9 /* StringLiteral */) { - return undefined; - } - if (node.parent.kind === 265 /* PropertyAssignment */ && - node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && - node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ - || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (isEqualityExpression(node.parent)) { - // Get completions from the type of the other operand - // i.e. switch (a) { - // case '/*completion position*/' - // } - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker); - } - else if (ts.isCaseOrDefaultClause(node.parent)) { - // Get completions from the type of the switch expression - // i.e. x === '/*completion position' - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.parent.parent.expression), typeChecker); + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + } + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174 /* LiteralType */: + switch (node.parent.parent.kind) { + case 160 /* TypeReference */: + // TODO: GH#21168 + return undefined; + case 172 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265 /* PropertyAssignment */: + if (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && + node.parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181 /* ElementAccessExpression */: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 249 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" - return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); + return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); } } function pathCompletionsInfo(entries) { @@ -80188,11 +82848,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80212,11 +82872,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccess(node, typeChecker, target, log) { - var type = typeChecker.getTypeAtLocation(node.expression); + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80233,6 +82892,30 @@ var ts; } return undefined; } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */, + kind: "label" /* label */, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768 /* TypeParameter */) { @@ -80262,29 +82945,33 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; } + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; // 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.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var typeChecker = program.getTypeChecker(); var name = entryId.name; // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); @@ -80292,26 +82979,26 @@ var ts; case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1 /* JsDocTagName */: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2 /* JsDocTag */: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; } case "none": { // Didn't find a symbol with this name. See if we can find a keyword instead. - if (ts.some(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; })) { + if (allKeywordsCompletions().some(function (c) { return c.name === name; })) { return { name: name, kind: "keyword" /* keyword */, @@ -80328,28 +83015,30 @@ var ts; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo && symbolOriginInfo.type === "export" + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); - var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { host: host, + program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), getCanonicalFileName: getCanonicalFileName, - symbolToken: undefined, + symbolToken: ts.tryCast(previousToken, ts.isIdentifier), kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, - }); + }).slice(0, 1); // Only take the first code action return { sourceDisplay: sourceDisplay, codeActions: codeActions }; } function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { @@ -80369,14 +83058,70 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getRecommendedCompletion(currentToken, checker /*, symbolToOriginInfoMap: SymbolOriginInfoMap*/) { - var ty = checker.getContextualType(currentToken); + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */ + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); + function getRecommendedCompletion(currentToken, checker) { + var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; // Don't include make a recommended completion for an abstract class return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) ? getFirstSymbolInChain(symbol, currentToken, checker) : undefined; } + function getContextualType(currentToken, checker) { + var parent = currentToken.parent; + switch (currentToken.kind) { + case 71 /* Identifier */: + return getContextualTypeFromParent(currentToken, checker); + case 58 /* EqualsToken */: + return ts.isVariableDeclaration(parent) ? checker.getContextualType(parent.initializer) : + ts.isBinaryExpression(parent) ? checker.getTypeAtLocation(parent.left) : undefined; + case 94 /* NewKeyword */: + return checker.getContextualType(parent); + case 73 /* CaseKeyword */: + return getSwitchedType(ts.cast(currentToken.parent, ts.isCaseClause), checker); + default: + return isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(currentToken); + } + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 183 /* NewExpression */: + return checker.getContextualType(parent); + case 195 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 261 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); if (chain) @@ -80387,7 +83132,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -80402,7 +83146,7 @@ var ts; if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } else { // When completion is requested without "@", we will have check to make sure that @@ -80423,7 +83167,7 @@ var ts; // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 /* JsDocTag */ }; } } } @@ -80433,7 +83177,7 @@ var ts; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); @@ -80446,24 +83190,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3 /* JsDocParameterName */, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0 /* None */, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - }; - } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available @@ -80488,9 +83217,11 @@ var ts; // Also determine whether we are trying to complete with members of that node // or attributes of a JSX tag. var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; + var isJsxInitializer = false; var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location @@ -80500,18 +83231,19 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 180 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144 /* QualifiedName */: + node = parent.left; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; } } else if (sourceFile.languageVariant === 1 /* JSX */) { @@ -80543,14 +83275,15 @@ var ts; location = contextToken; } break; + case 257 /* JsxAttribute */: + isJsxInitializer = previousToken.kind === 58 /* EqualsToken */; + break; } } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; var symbols = []; var symbolToOriginInfoMap = []; @@ -80565,8 +83298,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -80574,8 +83306,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -80586,8 +83317,8 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; + var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284 /* JSDocParameterTag */: @@ -80600,9 +83331,7 @@ var ts; } function getTypeScriptMemberSymbols() { // Right of dot member completion list - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2 /* PropertyAccess */; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); @@ -80647,10 +83376,9 @@ var ts; symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); } else { - // Filter private properties for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (typeChecker.isValidPropertyAccessForCompletions((node.parent), type, symbol)) { symbols.push(symbol); } } @@ -80671,13 +83399,16 @@ var ts; } if (tryGetConstructorLikeCompletionContainer(contextToken)) { // no members, only keywords - isMemberCompletion = false; + completionKind = 5 /* None */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter keywordFilters = 2 /* ConstructorParameterKeywords */; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3 /* FunctionLikeBodyKeywords */; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -80690,14 +83421,14 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return true; } } } // Get all entities in the current scope. - isMemberCompletion = false; + completionKind = 5 /* None */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -80731,40 +83462,55 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 /* SourceFile */ || - scopeNode.kind === 197 /* TemplateExpression */ || - scopeNode.kind === 260 /* JsxExpression */ || - scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1 /* Global */; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (options.includeInsertTextCompletions && scopeNode.kind !== 269 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269 /* SourceFile */: + case 197 /* TemplateExpression */: + case 260 /* JsxExpression */: + case 208 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { + var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + if (isTypeCompletion) + keywordFilters = 4 /* TypeKeywords */; 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)) { return true; } - // This is an alias, follow what it aliases - if (symbol && symbol.flags & 2097152 /* Alias */) { - symbol = typeChecker.getAliasedSymbol(symbol); - } + symbol = ts.skipAlias(symbol, typeChecker); // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); } - if (insideJsDocTagTypeExpression || - (!isContextTokenValueLocation(contextToken) && - (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + if (isTypeCompletion) { // Its a type, but you can reach it by namespace.type as well return symbolCanBeReferencedAtTypeLocation(symbol); } @@ -80794,6 +83540,7 @@ var ts; return parentKind === 203 /* AsExpression */; } } + return false; } function symbolCanBeReferencedAtTypeLocation(symbol) { symbol = symbol.exportSymbol || symbol; @@ -80814,27 +83561,21 @@ var ts; ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; - var name = symbol.name; // Don't add a completion for a re-export, only for the original. - // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } - var isDefaultExport = name === "default"; + var isDefaultExport = symbol.name === "default" /* Default */; if (isDefaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(symbol); - if (localSymbol) { - symbol = localSymbol; - name = localSymbol.name; - } - else { - name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); - } + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -80972,8 +83713,7 @@ var ts; */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { @@ -80998,7 +83738,7 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; if (!canGetType && rootDeclaration.kind === 147 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); @@ -81046,7 +83786,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -81063,7 +83803,7 @@ var ts; */ function getGetClassLikeCompletionSymbols(classLikeDeclaration) { // We're looking up possible property names from parent type. - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements @@ -81214,6 +83954,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -81383,7 +84138,10 @@ var ts; case "yield": return true; } - return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + && !(ts.isClassLike(contextToken.parent) && position > previousToken.end); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; @@ -81416,9 +84174,9 @@ var ts; existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" /* Default */; }); } - return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" /* Default */ && !existingImportsOrExports.get(e.escapedName); }); } /** * Filters out completion suggestions for named imports or exports. @@ -81542,88 +84300,69 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + // 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) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { return undefined; - // 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 (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; - } } - // If the symbol is for a member of an object type and is the internal name of an ES - // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - if (symbol.flags & 106500 /* ClassMember */) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 /* _ */ && - escapedName.charCodeAt(1) === 95 /* _ */ && - escapedName.charCodeAt(2) === 64 /* at */) { + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3 /* MemberLike */: return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - // TODO: GH#18169 - return allowStringLiteral ? JSON.stringify(name) : undefined; + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + case 5 /* None */: + case 1 /* Global */: + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - return name; } // A cache of completion entries for keywords, these do not change between sessions var _keywordCompletions = []; - function getKeywordCompletions(keywordFilter) { - var completions = _keywordCompletions[keywordFilter]; - if (completions) { - return completions; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); } - return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); - function generateKeywordCompletions(keywordFilter) { + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - return getAllKeywordCompletions(); + // "undefined" is a global variable, so don't need a keyword completion for it. + return kind !== 139 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: - return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + return isClassMemberCompletionKeyword(kind); case 2 /* ConstructorParameterKeywords */: - return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); - } - } - function getAllKeywordCompletions() { - var allKeywordsCompletions = []; - for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { - // "undefined" is a global variable, so don't need a keyword completion for it. - if (i === 139 /* UndefinedKeyword */) - continue; - allKeywordsCompletions.push({ - name: ts.tokenToString(i), - kind: "keyword" /* keyword */, - kindModifiers: "" /* none */, - sortText: "0" - }); + return isConstructorParameterCompletionKeyword(kind); + case 3 /* FunctionLikeBodyKeywords */: + return isFunctionLikeBodyCompletionKeyword(kind); + case 4 /* TypeKeywords */: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); } - return allKeywordsCompletions; - } - function getFilteredKeywordCompletions(filterFn) { - return ts.filter(getKeywordCompletions(0 /* None */), function (entry) { return filterFn(entry.name); }); - } + })); } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -81655,14 +84394,32 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } - function isEqualityExpression(node) { - return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + case 117 /* AbstractKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 139 /* UndefinedKeyword */: + return false; + } + return true; } function isEqualityOperatorKind(kind) { - return kind === 32 /* EqualsEqualsToken */ || - kind === 33 /* ExclamationEqualsToken */ || - kind === 34 /* EqualsEqualsEqualsToken */ || - kind === 35 /* ExclamationEqualsEqualsToken */; + switch (kind) { + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + return true; + default: + return false; + } } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { @@ -81696,8 +84453,7 @@ var ts; } /** * Gets all properties on a type, but if that type is a union of several types, - * tries to only include those types which declare properties, not methods. - * This ensures that we don't try providing completions for all the methods on e.g. Array. + * excludes array-like types or callable/constructable types. */ function getPropertiesForCompletion(type, checker, isForAccess) { if (!(type.flags & 131072 /* Union */)) { @@ -81719,11 +84475,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Note that getTouchingWord indicates failure by returning the sourceFile node. - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { @@ -81732,7 +84484,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -81742,8 +84494,8 @@ var ts; kind: "none" /* none */ }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -82538,7 +85290,7 @@ var ts; } function isNameMatch(name) { // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports - return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default"; + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; } } /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ @@ -82752,7 +85504,7 @@ var ts; // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = symbolName(importedSymbol); - if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { + if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } @@ -82816,7 +85568,7 @@ var ts; } FindAllReferences.getExportInfo = getExportInfo; function symbolName(symbol) { - if (symbol.escapedName !== "default") { + if (symbol.escapedName !== "default" /* Default */) { return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { @@ -82826,7 +85578,7 @@ var ts; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { - // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -82872,30 +85624,23 @@ var ts; FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); - if (!referencedSymbols || !referencedSymbols.length) { - return undefined; - } - var out = []; var checker = program.getTypeChecker(); - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - if (definition) { - out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }); - } - } - return out; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { // A node in a JSDoc comment can't have an implementation anyway. var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269 /* SourceFile */) { return undefined; } @@ -82915,7 +85660,7 @@ var ts; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -82923,14 +85668,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -82941,8 +85686,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_3 = def.node; var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_4 = def.node; @@ -82950,8 +85695,8 @@ var ts; } case "keyword": { var node_5 = def.node; - var name_6 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_6, kind: "keyword" /* keyword */, displayParts: [{ text: name_6, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case "this": { var node_6 = def.node; @@ -83069,10 +85814,11 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269 /* SourceFile */) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -83085,11 +85831,7 @@ var ts; // Could not find a symbol e.g. unknown identifier if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. - if (!options.implementations && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - // Can't have references to something that we have no symbol for. - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -83098,7 +85840,7 @@ var ts; } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleReferenceLocation(node) { - if (node.kind !== 9 /* StringLiteral */) { + if (node.kind !== 9 /* StringLiteral */ && node.kind !== 13 /* NoSubstitutionTemplateLiteral */) { return false; } switch (node.parent.kind) { @@ -83173,11 +85915,11 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); // Compute the meaning from the location and the symbol it references 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 state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, node, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); @@ -83201,8 +85943,22 @@ var ts; } return result; } + function getSpecialSearchKind(node) { + switch (node.kind) { + case 123 /* ConstructorKeyword */: + return 1 /* Constructor */; + case 71 /* Identifier */: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2 /* Class */; + } + // falls through + default: + return 0 /* None */; + } + } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -83211,18 +85967,29 @@ var ts; // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. return checker.getImmediateAliasedSymbol(symbol); } - return symbol; - } + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); /** * Holds all state needed for the finding references. * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { function State(sourceFiles, - /** True if we're searching for constructor references. */ - isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; - this.isForConstructor = isForConstructor; + this.specialSearchKind = specialSearchKind; this.checker = checker; this.cancellationToken = cancellationToken; this.searchMeaning = searchMeaning; @@ -83264,6 +86031,9 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); @@ -83576,11 +86346,18 @@ var ts; getReferenceForShorthandProperty(referenceSymbol, search, state); return; } - if (state.isForConstructor) { - findConstructorReferences(referenceLocation, sourceFile, search, state); - } - else { - addReference(referenceLocation, relatedSymbol, search.location, state); + switch (state.specialSearchKind) { + case 0 /* None */: + addReference(referenceLocation, relatedSymbol, search.location, state); + break; + case 1 /* Constructor */: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } @@ -83679,22 +86456,46 @@ var ts; } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ - function findConstructorReferences(referenceLocation, sourceFile, search, state) { + function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { addReference(referenceLocation, search.symbol, search.location, state); } - var pusher = state.referenceAdder(search.symbol, search.location); + var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. - findOwnConstructorReferences(search.symbol, sourceFile, pusher); + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } else { // If this class appears in `extends C`, then the extending class' "super" calls are references. var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); - if (classExtending && ts.isClassLike(classExtending)) { - findSuperConstructorAccesses(classExtending, pusher); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + } + } + } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, search.location, state); + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.parent.name === referenceLocation); + // This is the class declaration. + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + } + } + function addStaticThisReferences(classLike, pusher) { + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { + continue; } + member.body.forEachChild(function cb(node) { + if (node.kind === 99 /* ThisKeyword */) { + pusher(node); + } + else if (!ts.isFunctionLike(node)) { + node.forEachChild(cb); + } + }); } } function getPropertyAccessExpressionFromRightHandSide(node) { @@ -83768,7 +86569,7 @@ var ts; var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { var parent = containingTypeReference.parent; - if (ts.isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) { + if (ts.hasType(parent) && parent.type === containingTypeReference && ts.hasInitializer(parent) && isImplementationExpression(parent.initializer)) { addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { @@ -84063,7 +86864,7 @@ var ts; // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol, location, checker, implementations) { // The search set contains at least the current symbol - var result = [symbol]; + var result = []; var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { // If the location is name of property symbol from object literal destructuring pattern @@ -84078,9 +86879,10 @@ var ts; // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - ts.addRange(result, checker.getRootSymbols(contextualSymbol)); - }); + for (var _i = 0, _a = getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker); _i < _a.length; _i++) { + var contextualSymbol = _a[_i]; + addRootSymbols(contextualSymbol); + } /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -84116,9 +86918,7 @@ var ts; // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { var rootSymbol = _a[_i]; - if (rootSymbol !== sym) { - result.push(rootSymbol); - } + result.push(rootSymbol); // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); @@ -84201,9 +87001,7 @@ var ts; // compare to our searchSymbol var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); - }); + var contextualSymbol = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), findRootSymbol); if (contextualSymbol) { return contextualSymbol; } @@ -84229,7 +87027,7 @@ var ts; function findRootSymbol(sym) { // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) // Or a union property, use its underlying unioned symbols - return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { // if it is in the list, then we are done if (search.includes(rootSymbol)) { return rootSymbol; @@ -84239,11 +87037,11 @@ var ts; // parent symbol if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { // Parents will only be defined if implementations is true - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })) { return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); return ts.find(result, search.includes); } return undefined; @@ -84263,26 +87061,11 @@ var ts; } /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { - var objectLiteral = node.parent; - var contextualType = checker.getContextualType(objectLiteral); + var contextualType = checker.getContextualType(node.parent); var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol = contextualType.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - if (contextualType.flags & 131072 /* Union */) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; + var symbol = contextualType && name && contextualType.getProperty(name); + return symbol ? [symbol] : + contextualType && contextualType.flags & 131072 /* Union */ ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -84317,14 +87100,12 @@ var ts; if (!node) { return false; } - else if (ts.isVariableLike(node)) { - if (node.initializer) { - return true; - } - else if (node.kind === 227 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } + else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { + return true; + } + else if (node.kind === 227 /* VariableDeclaration */) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } else if (ts.isFunctionLike(node)) { return !!node.body || ts.hasModifier(node, 2 /* Ambient */); @@ -84408,21 +87189,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - // Might still be on jsdoc, so keep looking. - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { @@ -84510,6 +87279,21 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -84517,26 +87301,14 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_6; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -84580,59 +87352,29 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 123 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + if (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */ && symbol.flags & 32 /* Class */) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; - } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; + return undefined; } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -84682,6 +87424,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -84720,7 +87463,6 @@ var ts; (function (ts) { var JsDoc; (function (JsDoc) { - var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -84774,18 +87516,29 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289 /* JSDocPropertyTag */: + return [declaration]; + case 288 /* JSDocTypedefTag */: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; @@ -84816,10 +87569,13 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } /** @@ -84830,7 +87586,7 @@ var ts; function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -84911,9 +87667,16 @@ var ts; /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. - * Invalid positions are - * - within comments, strings (including template literals and regex), and JSXText - * - within a token + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations * * Hosts should ideally check that: * - The line is all whitespace up to 'position' before performing the insertion. @@ -84936,29 +87699,35 @@ var ts; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - // if climbing the tree did not find a declaration with parameters, complete to a single line comment - return singleLineTemplate; + return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.kind === 10 /* JsxText */) { + if (commentOwner.getStart() < position) { return undefined; } - if (commentOwner.getStart() < position || parameters.length === 0) { - // if climbing the tree found a declaration with parameters but the request was made inside it - // or if there are no parameters, complete to a single line comment - return singleLineTemplate; + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = parameters.map(function (_a, i) { - var name = _a.name; - var nameText = ts.isIdentifier(name) ? name.text : "param" + i; - var type = isJavaScriptFile ? "{any} " : ""; - return indentationStr + " * @param " + type + nameText + newLine; - }).join(""); + var docParams = ""; + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 /* Identifier */ ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } + } // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -84984,16 +87753,28 @@ var ts; case 151 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 149 /* PropertySignature */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 232 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; case 209 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; } case 269 /* SourceFile */: return undefined; + case 234 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 234 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 195 /* BinaryExpression */: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { @@ -85002,10 +87783,6 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } - case 10 /* JsxText */: { - var parameters_3 = ts.emptyArray; - return { commentOwner: commentOwner, parameters: parameters_3 }; - } } } } @@ -85211,8 +87988,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_7.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -85343,7 +88120,7 @@ var ts; if (!shouldKeepItem(declaration, checker)) { continue; } - // It was a match! If the pattern has dots in it, then also see if the + // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. var containerMatches = matches; if (patternMatcher.patternContainsDots) { @@ -85372,8 +88149,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -85442,8 +88219,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -87088,7 +89865,7 @@ var ts; // import "mod"; // import d from "mod" // import {a as A } from "mod"; - // import * as NS from "mod" + // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); // import("mod"); @@ -87188,9 +89965,16 @@ var ts; symbol.parent.flags & 1536 /* Module */) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9 /* StringLiteral */) { @@ -87424,7 +90208,7 @@ var ts; function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may // also just have nodes without commas. For example "Foo(a b c)" will have 3 - // args without commas. We want to find what index we're at. So we count + // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. // @@ -87450,12 +90234,12 @@ var ts; // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there - // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // is a small subtlety. If you have "Foo(a,)", then the child list will just have // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); @@ -87476,9 +90260,11 @@ var ts; // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // + // tslint:disable no-double-space // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -87525,9 +90311,8 @@ var ts; // Otherwise, we will not show signature help past the expression. // For example, // - // ` ${ 1 + 1 foo(10) - // | | - // + // ` ${ 1 + 1 foo(10) + // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 197 /* TemplateExpression */) { @@ -87569,6 +90354,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -87584,14 +90370,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -87599,7 +90391,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -87620,7 +90420,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -87631,7 +90432,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -87746,13 +90548,17 @@ var ts; return "" /* unknown */; } function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) : "" /* none */; + var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ? + "optional" /* optionalModifier */ + : "" /* none */; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -87762,6 +90568,8 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var printer; + var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -87829,14 +90637,14 @@ var ts; displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -87877,6 +90685,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) @@ -87892,14 +90701,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -87907,10 +90716,10 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); @@ -87920,7 +90729,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); @@ -87928,7 +90737,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); @@ -87956,12 +90765,12 @@ var ts; else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example - // type list = T[]; // Both T will go through same code path + // type list = T[]; // Both T will go through same code path addInPrefix(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -87986,7 +90795,23 @@ var ts; } } if (symbolFlags & 2097152 /* Alias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -88032,7 +90857,7 @@ var ts; if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); } else { @@ -88049,7 +90874,8 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -88100,26 +90926,45 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias" /* alias */); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92 /* InKeyword */)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); - if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -88142,7 +90987,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88157,7 +91002,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -88671,8 +91517,12 @@ var ts; for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); @@ -88702,7 +91552,7 @@ var ts; // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator @@ -88720,17 +91570,17 @@ var ts; rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace + // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // For functions and control block place } on a new line [multi-line rule] rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), // Space/new line after }. @@ -88817,7 +91667,7 @@ var ts; rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), // decorators - rule("SpaceBeforeAt", anyToken, 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ @@ -88843,8 +91693,8 @@ var ts; // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2 /* Space */), - rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8 /* Delete */), + rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), // Insert space after function keyword for anonymous functions rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), @@ -88899,8 +91749,10 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; - // These rules are lower in priority than user-configurable + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), @@ -88908,13 +91760,13 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - // No space before and after indexer - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2 /* Space */), + rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; @@ -89004,6 +91856,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 /* PropertyDeclaration */ || + contextKind === 149 /* PropertySignature */ || + contextKind === 147 /* Parameter */ || + contextKind === 227 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196 /* ConditionalExpression */; } @@ -89149,11 +92012,11 @@ var ts; function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } - function isNonJsxElementContext(context) { - return context.contextNode.kind !== 250 /* JsxElement */; + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 250 /* JsxElement */ && context.contextNode.kind !== 254 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 260 /* JsxExpression */; + return context.contextNode.kind === 260 /* JsxExpression */ || context.contextNode.kind === 259 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { return context.nextTokenParent.kind === 257 /* JsxAttribute */; @@ -89675,29 +92538,32 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1 /* Unknown */) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -89731,67 +92597,55 @@ var ts; case 18 /* CloseBraceToken */: case 22 /* CloseBracketToken */: case 20 /* CloseParenToken */: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - // if this token is the first token following the list of decorators, we do not need to indent - return indentation; - } - } - switch (kind) { - // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: - return indentation; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: { - if (container.kind === 252 /* JsxOpeningElement */ || - container.kind === 253 /* JsxClosingElement */ || - container.kind === 251 /* JsxSelfClosingElement */) { - return indentation; - } - break; - } - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: { - if (container.kind !== 173 /* MappedType */) { - return indentation; - } - break; - } - } - // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 17 /* OpenBraceToken */: + case 18 /* CloseBraceToken */: + case 19 /* OpenParenToken */: + case 20 /* CloseParenToken */: + case 82 /* ElseKeyword */: + case 106 /* WhileKeyword */: + case 57 /* AtToken */: + return false; + case 41 /* SlashToken */: + case 29 /* GreaterThanToken */: + switch (container.kind) { + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: + return false; + } + break; + case 21 /* OpenBracketToken */: + case 22 /* CloseBracketToken */: + if (container.kind !== 173 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; } @@ -89814,7 +92668,7 @@ var ts; // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes - // such tokens will be consumed in processChildNode for for the child that follows them + // such tokens will be consumed in processChildNode for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { @@ -90036,23 +92890,25 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0 /* None */; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAction = 2 /* LineRemoved */; - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); - } - } - else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAction = 1 /* LineAdded */; - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -90200,14 +93056,16 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1 /* Ignore */: // no action required - return; + return 0 /* None */; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } break; case 4 /* NewLine */: @@ -90215,25 +93073,27 @@ var ts; // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } - break; } + return 0 /* None */; } } var LineAction; @@ -90246,7 +93106,7 @@ var ts; * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword - tokenAtPosition, predicate) { + tokenAtPosition, predicate) { if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { @@ -90345,12 +93205,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -90360,20 +93220,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -90693,11 +93546,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1 /* Unknown */; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: @@ -90817,6 +93672,7 @@ var ts; case 176 /* ArrayBindingPattern */: case 175 /* ObjectBindingPattern */: case 252 /* JsxOpeningElement */: + case 255 /* JsxOpeningFragment */: case 251 /* JsxSelfClosingElement */: case 260 /* JsxExpression */: case 151 /* MethodSignature */: @@ -90862,6 +93718,8 @@ var ts; (!!child.namedBindings && child.namedBindings.kind !== 242 /* NamedImports */); case 250 /* JsxElement */: return childKind !== 253 /* JsxClosingElement */; + case 254 /* JsxFragment */: + return childKind !== 256 /* JsxClosingFragment */; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -91027,10 +93885,13 @@ var ts; this.formatContext = formatContext; this.validator = validator; this.changes = []; + this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + // Map from class id to nodes to insert at the start + this.nodesInsertedAtClassStarts = ts.createMap(); this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -91045,14 +93906,14 @@ var ts; if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -91069,6 +93930,9 @@ var ts; this.deleteNode(sourceFile, node); return this; } + var id = ts.getNodeId(node); + ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); + this.deletedNodesInLists[id] = true; if (index !== containingList.length - 1) { var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { @@ -91082,9 +93946,17 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); + var prev = containingList[index - 1]; + if (this.deletedNodesInLists[ts.getNodeId(prev)]) { + var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + var end = getAdjustedEndPosition(sourceFile, node, {}); + this.deleteRange(sourceFile, { pos: pos, end: end }); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); + if (previousToken && isSeparator(node, previousToken)) { + this.deleteNodeRange(sourceFile, previousToken, node); + } } } return this; @@ -91126,37 +93998,93 @@ var ts; }); return this; }; - ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); - }; - ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes) { + this.replaceWithMultiple(sourceFile, oldNode.getStart(sourceFile), oldNode.getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; - ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); - }; - ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes) { + this.replaceWithMultiple(sourceFile, ts.first(oldNodes).getStart(sourceFile), ts.last(oldNodes).getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; - ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); }; - ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { - if (options === void 0) { options = {}; } - if ((ts.isStatementButNotDeclaration(after)) || + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { + var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { + return { suffix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var startPosition = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + var firstMember = ts.firstOrUndefined(cls.members); + if (!firstMember) { + var id = ts.getNodeId(cls).toString(); + var newMembers = this.nodesInsertedAtClassStarts.get(id); + if (newMembers) { + ts.Debug.assert(newMembers.sourceFile === sourceFile && newMembers.cls === cls); + newMembers.members.push(newElement); + } + else { + this.nodesInsertedAtClassStarts.set(id, { sourceFile: sourceFile, cls: cls, members: [newElement] }); + } + } + else { + this.insertNodeBefore(sourceFile, firstMember, newElement); + } + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + if (ts.isStatementButNotDeclaration(after) || after.kind === 150 /* PropertyDeclaration */ || after.kind === 149 /* PropertySignature */ || after.kind === 151 /* MethodSignature */) { @@ -91172,8 +94100,20 @@ var ts; }); } } - var endPosition = getAdjustedEndPosition(sourceFile, after, options); - return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, this.getInsertNodeAfterOptions(after)); + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + } + else if (ts.isStatement(node) || ts.isClassElement(node) || ts.isTypeElement(node)) { + return { suffix: this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(node)) { + return { prefix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -91314,8 +94254,19 @@ var ts; } return this; }; + ChangeTracker.prototype.finishInsertNodeAtClassStart = function () { + var _this = this; + this.nodesInsertedAtClassStarts.forEach(function (_a) { + var sourceFile = _a.sourceFile, cls = _a.cls, members = _a.members; + var newCls = cls.kind === 230 /* ClassDeclaration */ + ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) + : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); + _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + }); + }; ChangeTracker.prototype.getChanges = function () { var _this = this; + this.finishInsertNodeAtClassStart(); var changesPerFile = ts.createMap(); // group changes per file for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { @@ -91495,6 +94446,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -91533,12 +94516,53 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; }()); + function getInsertionPositionAtSourceFileTop(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -91546,24 +94570,33 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var codeFixes = []; - function registerCodeFix(codeFix) { - ts.forEach(codeFix.errorCodes, function (error) { - var fixes = codeFixes[error]; - if (!fixes) { - fixes = []; - codeFixes[error] = fixes; - } - fixes.push(codeFix); - }); + var codeFixRegistrations = []; + var fixIdToRegistration = ts.createMap(); + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + var registrations = codeFixRegistrations[error]; + if (!registrations) { + registrations = []; + codeFixRegistrations[error] = registrations; + } + registrations.push(reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } } codefix.registerCodeFix = registerCodeFix; function getSupportedErrorCodes() { - return Object.keys(codeFixes); + return Object.keys(codeFixRegistrations); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; function getFixes(context) { - var fixes = codeFixes[context.errorCode]; + var fixes = codeFixRegistrations[context.errorCode]; var allActions = []; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); @@ -91582,6 +94615,42 @@ var ts; return allActions; } codefix.getFixes = getFixes; + function getAllFixes(context) { + // Currently fixId is always a string. + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); + }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function codeFixAllWithTextChanges(context, errorCodes, use) { + var changes = []; + eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); + changes.sort(function (a, b) { return b.span.start - a.span.start; }); + return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); + } + codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91592,14 +94661,15 @@ var ts; // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - return ts.flatMapIter(refactors.values(), function (refactor) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); - }); + })); } refactor_1.getApplicableRefactors = getApplicableRefactors; function getEditsForRefactor(context, refactorName, actionName) { @@ -91618,22 +94688,24 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var decorator = ts.getAncestor(token, 148 /* Decorator */); - ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); - var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, decorator.expression, replacement); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), - changes: changeTracker.getChanges() - }]; - } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91641,27 +94713,36 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var qualifiedName = ts.getAncestor(token, 144 /* QualifiedName */); - ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); - if (!ts.isIdentifier(qualifiedName.left)) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); } - var leftText = qualifiedName.left.getText(sourceFile); - var rightText = qualifiedName.right.getText(sourceFile); - var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, qualifiedName, replacement); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), - changes: changeTracker.getChanges() - }]; - } + }); }, }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91669,55 +94750,61 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code], - getCodeActions: getActionForClassLikeIncorrectImplementsInterface + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); + if (changes.length === 0) + return undefined; + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); + return { description: description, changes: changes, fixId: fixId }; + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + } + } + }); + }, }); - function getActionForClassLikeIncorrectImplementsInterface(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var classDeclaration = ts.getContainingClass(token); - if (!classDeclaration) { - return undefined; - } - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); + function getClass(sourceFile, pos) { + var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)); + ts.Debug.assert(!!classDeclaration); + return classDeclaration; + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); var classType = checker.getTypeAtLocation(classDeclaration); - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(classDeclaration); - var hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, 1 /* Number */); - var hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, 0 /* String */); - var result = []; - for (var _i = 0, implementedTypeNodes_2 = implementedTypeNodes; _i < implementedTypeNodes_2.length; _i++) { - var implementedTypeNode = implementedTypeNodes_2[_i]; - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - var implementedType = checker.getTypeAtLocation(implementedTypeNode); - var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); - var newNodes = []; - createAndAddMissingIndexSignatureDeclaration(implementedType, 1 /* Number */, hasNumericIndexSignature, newNodes); - createAndAddMissingIndexSignatureDeclaration(implementedType, 0 /* String */, hasStringIndexSignature, newNodes); - newNodes = newNodes.concat(codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker)); - var message = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - if (newNodes.length > 0) { - pushAction(result, newNodes, message); - } + if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - return result; - function createAndAddMissingIndexSignatureDeclaration(type, kind, hasIndexSigOfKind, newNodes) { - if (hasIndexSigOfKind) { - return; - } + if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); - if (!indexInfoOfKind) { - return; + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); } - var newIndexSignatureDeclaration = checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration); - newNodes.push(newIndexSignatureDeclaration); - } - function pushAction(result, newNodes, description) { - result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -91727,157 +94814,175 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ]; + var fixId = "addMissingMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, - ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], - getCodeActions: getActionsForAddMissingMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var addMember = inJs ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenNames = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var program = context.program; + var info = getInfo(diag.file, diag.start, program.getTypeChecker()); + if (!info) + return; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + if (!ts.addToSeen(seenNames, token.text)) { + return; + } + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + } + else { + if (inJs) { + addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); + addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + } + } + }); + }, }); - function getActionsForAddMissingMember(context) { - var tokenSourceFile = context.sourceFile; - var start = context.span.start; + function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(tokenSourceFile, start, /*includeJsDocComment*/ false); - if (token.kind !== 71 /* Identifier */) { + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false); + if (!ts.isIdentifier(token)) { + return undefined; + } + var classAndMakeStatic = getClassAndMakeStatic(token, checker); + if (!classAndMakeStatic) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent)) { + var classDeclaration = classAndMakeStatic.classDeclaration, makeStatic = classAndMakeStatic.makeStatic; + var classDeclarationSourceFile = classDeclaration.getSourceFile(); + var inJs = ts.isInJavaScriptFile(classDeclarationSourceFile); + var call = ts.tryCast(token.parent.parent, ts.isCallExpression); + return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; + } + function getClassAndMakeStatic(token, checker) { + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) { return undefined; } - var tokenName = token.getText(tokenSourceFile); - var makeStatic = false; - var classDeclaration; - if (token.parent.expression.kind === 99 /* ThisKeyword */) { + if (parent.expression.kind === 99 /* ThisKeyword */) { var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); if (!ts.isClassElement(containingClassMemberDeclaration)) { return undefined; } - classDeclaration = containingClassMemberDeclaration.parent; + var classDeclaration = containingClassMemberDeclaration.parent; // Property accesses on `this` in a static method are accesses of a static member. - makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */); + return ts.isClassLike(classDeclaration) ? { classDeclaration: classDeclaration, makeStatic: ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */) } : undefined; } else { - var checker = context.program.getTypeChecker(); - var leftExpression = token.parent.expression; - var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 65536 /* Object */) { - var symbol = leftExpressionType.symbol; - if (symbol.flags & 32 /* Class */) { - classDeclaration = symbol.declarations && symbol.declarations[0]; - if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { - // The expression is a class symbol but the type is not the instance-side. - makeStatic = true; - } - } + var leftExpressionType = checker.getTypeAtLocation(parent.expression); + var symbol = leftExpressionType.symbol; + if (!(leftExpressionType.flags & 65536 /* Object */ && symbol.flags & 32 /* Class */)) { + return undefined; } + var classDeclaration = ts.cast(ts.first(symbol.declarations), ts.isClassLike); + // The expression is a class symbol but the type is not the instance-side. + return { classDeclaration: classDeclaration, makeStatic: leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol) }; } - if (!classDeclaration || !ts.isClassLike(classDeclaration)) { + } + function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + if (changes.length === 0) return undefined; - } - var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); - var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); - return ts.isInJavaScriptFile(classDeclarationSourceFile) ? - getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : - getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); - function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ false); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - if (makeStatic) { - if (classDeclaration.kind === 200 /* ClassExpression */) { - return actions; - } - var className = classDeclaration.name.getText(); - var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); - var initializeStaticAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), - changes: staticInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeStaticAction); - return actions; - } - else { - var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); - if (!classConstructor) { - return actions; - } - var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); - var initializeAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), - changes: propertyInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeAction); - return actions; - } - } - function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ true); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - var typeNode; - if (token.parent.parent.kind === 195 /* BinaryExpression */) { - var binaryExpression = token.parent.parent; - var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); - } - typeNode = typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); - var property = ts.createProperty( - /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, - /*questionToken*/ undefined, typeNode, - /*initializer*/ undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; - actions = ts.append(actions, { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: propertyChangeTracker.getChanges() - }); - if (!makeStatic) { - // Index signatures cannot have the static modifier. - var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); - var indexingParameter = ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, "x", - /*questionToken*/ undefined, stringTypeNode, - /*initializer*/ undefined); - var indexSignature = ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); - actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), - changes: indexSignatureChangeTracker.getChanges() - }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); + return { description: description, changes: changes, fixId: fixId }; + } + function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 200 /* ClassExpression */) { + return; } - return actions; + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); } - function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 182 /* CallExpression */) { - var callExpression = token.parent.parent; - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: methodDeclarationChangeTracker.getChanges() - }; + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); + } + } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 195 /* BinaryExpression */) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } + return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + } + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -91886,18 +94991,35 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], - getCodeActions: getActionsForCorrectSpelling + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context.program.getTypeChecker()); + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion); + }); }, }); - function getActionsForCorrectSpelling(context) { - var sourceFile = context.sourceFile; + function getInfo(sourceFile, pos, checker) { // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 - var checker = context.program.getTypeChecker(); + var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852 var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 71 /* Identifier */); @@ -91910,18 +95032,10 @@ var ts; ts.Debug.assert(name !== undefined, "name should be defined"); suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - if (suggestion) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: node.getStart(), length: node.getWidth() }, - newText: suggestion - }], - }], - }]; - } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); } function convertSemanticMeaningToSymbolFlags(meaning) { var flags = 0; @@ -91943,31 +95057,39 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixCannotFindModule"; + var errorCodes = [ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, - ], + errorCodes: errorCodes, 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, sourceFile.fileName, token.text); - return action && [action]; + var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); + return codeAction && [__assign({ fixId: fixId }, codeAction)]; }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { + var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + if (pkg) { + commands.push(getCommand(diag.file.fileName, pkg)); + } + }); }, }); - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + function getModuleName(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; + } + function getCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function getTypesPackageNameToInstall(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: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + // If !registry, registry not available yet, can't do anything. + return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; + } + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = getTypesPackageNameToInstall(host, moduleName); + return packageName === undefined ? undefined : { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), changes: [], - commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + commands: [getCommand(fileName, packageName)], }; } codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; @@ -91978,44 +95100,45 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code], - getCodeActions: getActionForClassLikeMissingAbstractMember - }); - codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code], - getCodeActions: getActionForClassLikeMissingAbstractMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + }); + return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); + }); }, }); - function getActionForClassLikeMissingAbstractMember(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; + function getClass(sourceFile, pos) { // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - if (ts.isClassLike(token.parent)) { - var classDeclaration = token.parent; - var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); - var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - var extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType); - var abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember); - var newNodes = codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker); - var changes = codefix.newNodesToChanges(newNodes, ts.getOpenBraceOfClassLike(classDeclaration, sourceFile), context); - if (changes && changes.length > 0) { - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), - changes: changes - }]; - } - } - return undefined; + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var classDeclaration = token.parent; + ts.Debug.assert(ts.isClassLike(classDeclaration)); + return classDeclaration; + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { - var decls = symbol.getDeclarations(); - ts.Debug.assert(!!(decls && decls.length > 0)); - var flags = ts.getModifierFlags(decls[0]); + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -92025,48 +95148,54 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 99 /* ThisKeyword */) { - return undefined; - } - var constructor = ts.getContainingFunction(token); - var superCall = findSuperCall(constructor.body); - if (!superCall) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) return undefined; - } - // figure out if the `this` access is actually inside the supercall - // i.e. super(this.a), since in that case we won't suggest a fix - if (superCall.expression && superCall.expression.kind === 182 /* CallExpression */) { - var expressionArguments = superCall.expression.arguments; - for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { - var arg = expressionArguments_1[_i]; - if (arg.expression === token) { - return undefined; - } - } - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); - changeTracker.deleteNode(sourceFile, superCall); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), - changes: changeTracker.getChanges() - }]; - function findSuperCall(n) { - if (n.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { - return n; - } - if (ts.isFunctionLike(n)) { - return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); // Ensure we only do this once per class. + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); } - return ts.forEachChild(n, findSuperCall); - } - } + }); + }, }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.deleteNode(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 99 /* ThisKeyword */); + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92074,23 +95203,30 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 123 /* ConstructorKeyword */) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), - changes: changeTracker.getChanges() - }]; - } + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92098,40 +95234,51 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var classDeclNode = ts.getContainingClass(token); - if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceRange(sourceFile, { pos: extendsToken.getStart(), end: extendsToken.end }, ts.createToken(108 /* ImplementsKeyword */)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === 85 /* ExtendsKeyword */ && + heritageClauses[1].token === 108 /* ImplementsKeyword */) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */)); + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; } - var heritageClauses = classDeclNode.heritageClauses; - if (!(heritageClauses && heritageClauses.length > 0)) { - return undefined; - } - var extendsToken = heritageClauses[0].getFirstToken(); - if (!(extendsToken && extendsToken.kind === 85 /* ExtendsKeyword */)) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); - // We replace existing keywords with commas. - for (var i = 1; i < heritageClauses.length; i++) { - var keywordToken = heritageClauses[i].getFirstToken(); - if (keywordToken) { - changeTracker.replaceNode(sourceFile, keywordToken, ts.createToken(26 /* CommaToken */)); - } - } - var result = [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), - changes: changeTracker.getChanges() - }]; - return result; + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); } - }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92139,22 +95286,27 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var errorCodes = [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 71 /* Identifier */) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), - changes: changeTracker.getChanges() - }]; - } + var token = getNode(sourceFile, context.span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isIdentifier); + } + function doChange(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92162,183 +95314,311 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, - ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - // this handles var ["computed"] = 12; - if (token.kind === 21 /* OpenBracketToken */) { - token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); + var token = getToken(sourceFile, context.span.start); + var result = []; + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + if (deletion.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); + result.push({ description: description, changes: deletion, fixId: fixIdDelete }); } - switch (token.kind) { - case 71 /* Identifier */: - return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); - case 150 /* PropertyDeclaration */: - case 241 /* NamespaceImport */: - return [deleteNode(token.parent)]; + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + if (prefix.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); + result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = getToken(diag.file, diag.start); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + tryDeleteDeclaration(changes, sourceFile, token); + break; default: - return deleteDefault(); + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); }, + }); + function getToken(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + // this handles var ["computed"] = 12; + return token.kind === 21 /* OpenBracketToken */ ? ts.getTokenAtPosition(sourceFile, pos + 1, /*includeJsDocComment*/ false) : token; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + // Don't offer to prefix a property. + if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 147 /* Parameter */: + return true; + case 227 /* VariableDeclaration */: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 217 /* ForOfStatement */: + case 216 /* ForInStatement */: + return true; + } } - function deleteDefault() { - if (ts.isDeclarationName(token)) { - return [deleteNode(token.parent)]; + } + return false; + } + function tryDeleteDeclaration(changes, sourceFile, token) { + switch (token.kind) { + case 71 /* Identifier */: + tryDeleteIdentifier(changes, sourceFile, token); + break; + case 150 /* PropertyDeclaration */: + case 241 /* NamespaceImport */: + changes.deleteNode(sourceFile, token.parent); + break; + default: + tryDeleteDefault(changes, sourceFile, token); + } + } + function tryDeleteDefault(changes, sourceFile, token) { + if (ts.isDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent.parent); + } + } + function tryDeleteIdentifier(changes, sourceFile, identifier) { + var parent = identifier.parent; + switch (parent.kind) { + case 227 /* VariableDeclaration */: + tryDeleteVariableDeclaration(changes, sourceFile, parent); + break; + case 146 /* TypeParameter */: + var typeParameters = parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + changes.deleteNodeRange(sourceFile, previousToken, nextToken); } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return [deleteNode(token.parent.parent)]; + else { + changes.deleteNodeInList(sourceFile, parent); + } + break; + case 147 /* Parameter */: + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } else { - return undefined; + changes.deleteNodeInList(sourceFile, parent); } - } - function prefixIdentifierWithUnderscore(identifier) { - var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), - changes: [{ - fileName: sourceFile.path, - textChanges: [{ - span: { start: startPosition, length: 0 }, - newText: "_" - }] - }] - }; - } - function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { - var parent = identifier.parent; - switch (parent.kind) { - case 227 /* VariableDeclaration */: - return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 146 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - return [deleteNodeRange(previousToken, nextToken)]; - } - else { - return [deleteNodeInList(parent)]; - } - case 147 /* Parameter */: - var functionDeclaration = parent.parent; - var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); - return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ? [deleteAction] - : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; - // handle case where 'import a = A;' - case 238 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); - return [deleteNode(importEquals)]; - case 243 /* ImportSpecifier */: - var namedImports = parent.parent; - if (namedImports.elements.length === 1) { - return deleteNamedImportBinding(namedImports); - } - else { - // delete import specifier - return [deleteNodeInList(parent)]; - } - case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' - var importClause = parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 239 /* ImportDeclaration */); - return [deleteNode(importDecl)]; - } - else { - // import |d,| * as ns from './file' - var start_6 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; - } - else { - return [deleteNode(importClause.name)]; - } - } - case 241 /* NamespaceImport */: - return deleteNamedImportBinding(parent); - default: - return deleteDefault(); + break; + // handle case where 'import a = A;' + case 238 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); + changes.deleteNode(sourceFile, importEquals); + break; + case 243 /* ImportSpecifier */: + var namedImports = parent.parent; + if (namedImports.elements.length === 1) { + tryDeleteNamedImportBinding(changes, sourceFile, namedImports); } - } - function deleteNamedImportBinding(namedBindings) { - if (namedBindings.parent.name) { - // Delete named imports while preserving the default import - // import d|, * as ns| from './file' - // import d|, { a }| from './file' - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; - } - return undefined; + else { + // delete import specifier + changes.deleteNodeInList(sourceFile, parent); + } + break; + case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + var importClause = parent; + if (!importClause.namedBindings) { + changes.deleteNode(sourceFile, ts.getAncestor(importClause, 239 /* ImportDeclaration */)); } else { - // Delete the entire import declaration - // |import * as ns from './file'| - // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); - return [deleteNode(importDecl)]; + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + changes.deleteNode(sourceFile, importClause.name); + } } + break; + case 241 /* NamespaceImport */: + tryDeleteNamedImportBinding(changes, sourceFile, parent); + break; + default: + tryDeleteDefault(changes, sourceFile, identifier); + break; + } + } + function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) { + if (namedBindings.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); } - // token.parent is a variableDeclaration - function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { - switch (varDecl.parent.parent.kind) { - case 215 /* ForStatement */: - var forStatement = varDecl.parent.parent; - var forInitializer = forStatement.initializer; - return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 217 /* ForOfStatement */: - var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); - var forOfInitializer = forOfStatement.initializer; - return [ - replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), - prefixIdentifierWithUnderscore(identifier) - ]; - case 216 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return [prefixIdentifierWithUnderscore(identifier)]; - default: - var variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return [deleteNode(variableStatement)]; - } - else { - return [deleteNodeInList(varDecl)]; - } + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); + changes.deleteNode(sourceFile, importDecl); + } + } + // token.parent is a variableDeclaration + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + switch (varDecl.parent.parent.kind) { + case 215 /* ForStatement */: { + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + changes.deleteNode(sourceFile, forInitializer); } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + break; } - function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); - } - function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); - } - function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); - } - function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); - } - function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); + case 217 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); + break; + case 216 /* ForInStatement */: + case 225 /* TryStatement */: + break; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + changes.deleteNode(sourceFile, variableStatement); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain)]; + if (typeNode.kind === 274 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); } - function makeChange(changeTracker) { + return actions; + function fix(type, fixId) { + var newText = typeString(type, checker); return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], + fixId: fixId, }; } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 274 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + }); } }); + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function createChange(declaration, sourceFile, newText) { + return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; + } + function typeString(type, checker) { + return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); + } + function isTypeContainer(node) { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case 203 /* AsExpression */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 229 /* FunctionDeclaration */: + case 154 /* GetAccessor */: + case 158 /* IndexSignature */: + case 173 /* MappedType */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 155 /* SetAccessor */: + case 232 /* TypeAliasDeclaration */: + case 185 /* TypeAssertionExpression */: + case 227 /* VariableDeclaration */: + return true; + default: + return false; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92346,62 +95626,72 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], - getCodeActions: getActionsForJSDocTypes + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, }); - function getActionsForJSDocTypes(context) { - var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - // NOTE: Some locations are not handled yet: - // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments - var decl = ts.findAncestor(node, function (n) { - return n.kind === 203 /* AsExpression */ || - n.kind === 156 /* CallSignature */ || - n.kind === 157 /* ConstructSignature */ || - n.kind === 229 /* FunctionDeclaration */ || - n.kind === 154 /* GetAccessor */ || - n.kind === 158 /* IndexSignature */ || - n.kind === 173 /* MappedType */ || - n.kind === 152 /* MethodDeclaration */ || - n.kind === 151 /* MethodSignature */ || - n.kind === 147 /* Parameter */ || - n.kind === 150 /* PropertyDeclaration */ || - n.kind === 149 /* PropertySignature */ || - n.kind === 155 /* SetAccessor */ || - n.kind === 232 /* TypeAliasDeclaration */ || - n.kind === 185 /* TypeAssertionExpression */ || - n.kind === 227 /* VariableDeclaration */; - }); - if (!decl) - return; - var checker = context.program.getTypeChecker(); - var jsdocType = decl.type; - if (!jsdocType) - return; - var original = ts.getTextOfNode(jsdocType); - var type = checker.getTypeFromTypeNode(jsdocType); - var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; - if (jsdocType.kind === 274 /* JSDocNullableType */) { - // for nullable types, suggest the flow-compatible `T | null | undefined` - // in addition to the jsdoc/closure-compatible `T | null` - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); - actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); - } - return actions; - } - function createAction(declaration, fileName, original, replacement) { + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + break; + case 188 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), - changes: [{ - fileName: fileName, - textChanges: [{ - span: { start: declaration.getStart(), length: declaration.getWidth() }, - newText: replacement - }] - }], + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) }; } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92417,7 +95707,10 @@ var ts; ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ], - getCodeActions: getImportCodeActions + getCodeActions: getImportCodeActions, + // TODO: GH#20315 + fixIds: [], + getAllCodeActions: ts.notImplemented, }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { @@ -92517,21 +95810,25 @@ var ts; return { description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), changes: changes, + // TODO: GH#20315 + fixId: undefined, kind: kind, moduleSpecifier: moduleSpecifier }; } function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var checker = context.program.getTypeChecker(); - var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + var program = context.program; + var checker = program.getTypeChecker(); + // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. + var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, + program: program, checker: checker, - compilerOptions: context.program.getCompilerOptions(), + compilerOptions: program.getCompilerOptions(), cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolToken.getText(), @@ -92568,7 +95865,10 @@ var ts; var declaration = declarations_13[_i]; var namespace = getNamespaceImportName(declaration); if (namespace) { - actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } } } @@ -92613,7 +95913,7 @@ var ts; } } function getCodeActionForNewImport(context, moduleSpecifier) { - var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var kind = context.kind, sourceFile = context.sourceFile, symbolName = context.symbolName; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); @@ -92626,10 +95926,10 @@ var ts; /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); var changes = ChangeTracker.with(context, function (changeTracker) { if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } else { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); + changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); } }); // if this file doesn't have any import statements, insert an import statement and then insert a new line @@ -92643,6 +95943,12 @@ var ts; literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); return literal; } + function usesJsExtensionOnImports(sourceFile) { + return ts.firstDefined(sourceFile.imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -92656,68 +95962,86 @@ var ts; ts.Debug.assertNever(kind); } } - function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + function getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; - var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); - if (!baseUrl) { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; + var addJsExtension = usesJsExtensionOnImports(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; } - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); }); // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) - return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + return ts.best(ts.arrayIterator(choicesForEachExportingModule), function (a, b) { return a[0].length < b[0].length; }); } codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } function getRelativePathNParents(relativePath) { var count = 0; for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { @@ -92731,10 +96055,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -92742,14 +96067,14 @@ var ts; 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); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -92764,12 +96089,12 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + return 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), options); + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); } }); } @@ -92877,15 +96202,25 @@ var ts; 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); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } - function removeExtensionAndIndexPostFix(fileName, options) { + function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); - return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + return addJsExtension + ? noExtension + ".js" + : ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -92905,7 +96240,7 @@ var ts; return [fromExistingImport]; } var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); - var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.program, ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); } function moduleSpecifierFromAnyImport(node) { @@ -92960,10 +96295,11 @@ var ts; * 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); + // Prefix the node instead of it replacing it, because this may be used for import completions and we don't want the text changes to overlap with the identifier being completed. + var changes = ChangeTracker.with(context, function (tracker) { + return tracker.changeIdentifierToPropertyAccess(sourceFile, namespacePrefix, symbolToken); + }); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes, "CodeChange", /*moduleSpecifier*/ undefined); } function getImportCodeActions(context) { var importFixContext = convertToImportCodeFixContext(context); @@ -92982,7 +96318,7 @@ var ts; } 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 */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */, /*excludeGlobals*/ false)); symbolName = symbol.name; } else { @@ -93021,11 +96357,12 @@ var ts; forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { // check if this symbol is already used var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); @@ -93037,6 +96374,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -93103,6 +96455,7 @@ var ts; // Need `|| "_"` to ensure result isn't empty. return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -93110,16 +96463,44 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); codefix.registerCodeFix({ - errorCodes: getApplicableDiagnosticCodes(), - getCodeActions: getDisableJsDiagnosticsCodeActions + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], + fixId: fixId, + }, + { + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [{ + span: { + start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, + length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 + }, + newText: "// @ts-nocheck" + newLineCharacter + }])], + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + fixId: undefined, + }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + if (err.start !== undefined) { + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); + } + }); }, }); - function getApplicableDiagnosticCodes() { - var allDiagnostcs = ts.Diagnostics; - return Object.keys(allDiagnostcs) - .filter(function (d) { return allDiagnostcs[d] && allDiagnostcs[d].category === ts.DiagnosticCategory.Error; }) - .map(function (d) { return allDiagnostcs[d].code; }); - } function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { var line = ts.getLineAndCharacterOfPosition(sourceFile, position).line; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); @@ -93144,32 +96525,6 @@ var ts; newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter }; } - function getDisableJsDiagnosticsCodeActions(context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { - return undefined; - } - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)] - }] - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { - start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, - length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 - }, - newText: "// @ts-nocheck" + newLineCharacter - }] - }] - }]; - } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -93177,64 +96532,33 @@ var ts; (function (ts) { var codefix; (function (codefix) { - function newNodesToChanges(newNodes, insertAfter, context) { - var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { - var newNode = newNodes_1[_i]; - changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); - } - var changes = changeTracker.getChanges(); - if (!ts.some(changes)) { - return changes; - } - ts.Debug.assert(changes.length === 1); - var consolidatedChanges = [{ - fileName: changes[0].fileName, - textChanges: [{ - span: changes[0].textChanges[0].span, - newText: changes[0].textChanges.reduce(function (prev, cur) { return prev + cur.newText; }, "") - }] - }]; - return consolidatedChanges; - } - codefix.newNodesToChanges = newNodesToChanges; /** * Finds members of the resolved type that are missing in the class pointed to by class decl * and generates source code for the missing members. * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, out) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); - var newNodes = []; - for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { - var symbol = missingMembers_1[_i]; - var newNode = createNewNodeForMemberSymbol(symbol, classDeclaration, checker); - if (newNode) { - if (Array.isArray(newNode)) { - newNodes = newNodes.concat(newNode); - } - else { - newNodes.push(newNode); - } + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); } } - return newNodes; } codefix.createMissingMemberNodes = createMissingMemberNodes; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function createNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -93245,10 +96569,10 @@ var ts; case 149 /* PropertySignature */: case 150 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); - var property = ts.createProperty( + out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, - /*initializer*/ undefined); - return property; + /*initializer*/ undefined)); + break; case 151 /* MethodSignature */: case 152 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff @@ -93260,70 +96584,65 @@ var ts; // correspondence of declarations and signatures. var signatures = checker.getSignaturesOfType(type, 0 /* Call */); if (!ts.some(signatures)) { - return undefined; + break; } if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody()); + break; } - var signatureDeclarations = []; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var signature = signatures_8[_i]; - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + outputMethod(signature, modifiers, name, createStubbedMethodBody()); } else { ts.Debug.assert(declarations.length === signatures.length); - var methodImplementingSignatures = createMethodImplementingSignatures(signatures, name, optional, modifiers); - signatureDeclarations.push(methodImplementingSignatures); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); } - return signatureDeclarations; - default: - return undefined; + break; } - function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); - if (signatureDeclaration) { - signatureDeclaration.decorators = undefined; - signatureDeclaration.modifiers = modifiers; - signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; - signatureDeclaration.body = body; - } - return signatureDeclaration; + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); } } - function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { - var parameters = createDummyParameters(callExpression.arguments.length, /*names*/ undefined, /*minArgumentCount*/ undefined, includeTypeScriptSyntax); - var typeParameters; - if (includeTypeScriptSyntax) { - var typeArgCount = ts.length(callExpression.typeArguments); - for (var i = 0; i < typeArgCount; i++) { - var name = typeArgCount < 8 ? String.fromCharCode(84 /* T */ + i) : "T" + i; - var typeParameter = ts.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined); - (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); - } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + if (!signatureDeclaration) { + return undefined; } - var newMethod = ts.createMethod( + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); + } + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + var typeArguments = _a.typeArguments, args = _a.arguments; + return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, /*asteriskToken*/ undefined, methodName, - /*questionToken*/ undefined, typeParameters, parameters, - /*type*/ includeTypeScriptSyntax ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, createStubbedMethodBody()); - return newMethod; + /*questionToken*/ undefined, + /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + }), + /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; - function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + function createDummyParameters(argCount, names, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { var newParameter = ts.createParameter( @@ -93332,7 +96651,7 @@ var ts; /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ addAnyType ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -93358,7 +96677,7 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -93377,7 +96696,6 @@ var ts; /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } - codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], @@ -93399,229 +96717,239 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ], - getCodeActions: getActionsForAddExplicitTypeAnnotation + errorCodes: errorCodes, + getCodeActions: function (_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + if (ts.isSourceFileJavaScript(sourceFile)) { + return undefined; // TODO: GH#20113 + } + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); + if (!fix) + return undefined; + var declaration = fix.declaration, textChanges = fix.textChanges; + var name = ts.getNameOfDeclaration(declaration); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); + return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var seenFunctions = ts.createMap(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + if (fix) + changes.push.apply(changes, fix.textChanges); + }); + }, }); - function getActionsForAddExplicitTypeAnnotation(_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var writer; - if (ts.isInJavaScriptFile(token)) { - return undefined; - } - switch (token.kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 131 /* ReadonlyKeyword */: - // Allowed - break; + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; default: - return undefined; + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!isAllowedTokenKind(token.kind)) { + return undefined; } - var containingFunction = ts.getContainingFunction(token); - var checker = program.getTypeChecker(); switch (errorCode) { // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - return getCodeActionForVariableDeclaration(token.parent); - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: - return getCodeActionForVariableUsage(token); + return getCodeActionForVariableDeclaration(token.parent, sourceFile, program, cancellationToken); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, sourceFile, program, cancellationToken); + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction); + return getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken); } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return getCodeActionForParameters(token.parent); + return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) + ? getCodeActionForParameters(token.parent, containingFunction, sourceFile, program, cancellationToken) + : undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; - } - return undefined; - function getCodeActionForVariableDeclaration(declaration) { - if (!ts.isIdentifier(declaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(declaration.name); - var typeString = type && typeToString(type, declaration); - if (!typeString) { - return undefined; - } - return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); - } - function getCodeActionForVariableUsage(token) { - var symbol = checker.getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 229 /* FunctionDeclaration */: - case 152 /* MethodDeclaration */: - case 153 /* Constructor */: - return true; - case 187 /* FunctionExpression */: - return !!declaration.name; - } - return false; + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; + default: + throw ts.Debug.fail(String(errorCode)); } - function getCodeActionForParameters(parameterDeclaration) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; - } - var types = inferTypeForParametersFromUsage(containingFunction) || - ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); - if (!types) { - return undefined; - } - var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (type && !parameter.type && !parameter.initializer) { - var typeString = typeToString(type, containingFunction); - return typeString ? { - span: { start: parameter.end, length: 0 }, - newText: ": " + typeString - } : undefined; - } - }).filter(function (c) { return !!c; }); - return textChanges.length ? [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: textChanges - }] - }] : undefined; - } - function getCodeActionForSetAccessor(setAccessorDeclaration) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || - inferTypeForVariableFromUsage(setAccessorParameter.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function isAllowedTokenKind(kind) { + switch (kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + return true; + default: + return false; } - function getCodeActionForGetAccessor(getAccessorDeclaration) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); - return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function getCodeActionForVariableDeclaration(declaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(declaration.name)) + return undefined; + var type = inferTypeForVariableFromUsage(declaration.name, sourceFile, program, cancellationToken); + return makeFix(declaration, declaration.name.getEnd(), type, program); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + return true; + case 187 /* FunctionExpression */: + return !!declaration.name; } - function createCodeActions(name, start, typeString) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: start, length: 0 }, - newText: typeString - }] - }] - }]; + return false; + } + function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; } - function getReferences(token) { - var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); - ts.Debug.assert(!!references, "Found no references!"); - ts.Debug.assert(references.length === 1, "Found more references than expected"); - return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, sourceFile, program, cancellationToken) : undefined; }); + if (!types) + return undefined; + // We didn't actually find a set of type inference positions matching each parameter position + if (containingFunction.parameters.length !== types.length) { + return undefined; } - function inferTypeForVariableFromUsage(token) { - return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { + var parameter = _a[0], type = _a[1]; + return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; + })); + return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration, sourceFile, program, cancellationToken) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; } - function inferTypeForParametersFromUsage(containingFunction) { - switch (containingFunction.kind) { - case 153 /* Constructor */: - case 187 /* FunctionExpression */: - case 229 /* FunctionDeclaration */: - case 152 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 153 /* Constructor */; - var searchToken = isConstructor ? - getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); - } - } - } - function getTypeAccessiblityWriter() { - if (!writer) { - var str_1 = ""; - var typeIsAccessible_1 = true; - var writeText = function (text) { return str_1 += text; }; - writer = { - string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { - typeIsAccessible_1 = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } - }; - } - writer.clear(); - return writer; + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, sourceFile, program, cancellationToken) || + inferTypeForVariableFromUsage(setAccessorParameter.name, sourceFile, program, cancellationToken); + return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); + } + function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; } - function typeToString(type, enclosingDeclaration) { - var writer = getTypeAccessiblityWriter(); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, sourceFile, program, cancellationToken); + var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20 /* CloseParenToken */, sourceFile); + return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + } + function makeFix(declaration, start, type, program) { + return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; + } + function makeChange(declaration, start, type, program) { + var typeString = type && typeToString(type, declaration, program.getTypeChecker()); + return typeString === undefined ? undefined : { span: ts.createTextSpan(start, 0), newText: ": " + typeString }; + } + function getReferences(token, sourceFile, program, cancellationToken) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), sourceFile, token.getStart(sourceFile)); + if (!references || references.length !== 1) { + return []; } - function getFirstChildOfKind(node, sourcefile, kind) { - for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { - var child = _a[_i]; - if (child.kind === kind) - return child; - } - return undefined; + return references[0].references.map(function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token, sourceFile, program, cancellationToken) { + return InferFromReference.inferTypeFromReferences(getReferences(token, sourceFile, program, cancellationToken), program.getTypeChecker(), cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + switch (containingFunction.kind) { + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 153 /* Constructor */; + var searchToken = isConstructor ? + ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, sourceFile, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); + } } } + function getTypeAccessiblityWriter(checker) { + var str = ""; + var typeIsAccessible = true; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return typeIsAccessible ? str : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + writeLine: function () { return writeText(" "); }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str = ""; typeIsAccessible = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } + }; + } + function typeToString(type, enclosingDeclaration, checker) { + var writer = getTypeAccessiblityWriter(checker); + checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); + return writer.getText(); + } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -93635,6 +96963,9 @@ var ts; } InferFromReference.inferTypeFromReferences = inferTypeFromReferences; function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (references.length === 0) { + return undefined; + } if (declaration.parameters) { var usageContext = {}; for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { @@ -93661,7 +96992,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; } } @@ -93873,12 +97204,12 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); @@ -93936,7 +97267,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); return isRestParameter ? checker.createArrayType(type) : type; } return undefined; @@ -93962,6 +97293,94 @@ var ts; })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + // This is the whole import statement, eg: + // import * as Bluebird from 'bluebird'; + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; + if (!ts.isImportDeclaration(node)) { + // No import quick fix for import calls + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + var replacement = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + var replacement_1 = ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 /* CallExpression */ : 183 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// /// /// @@ -93975,10 +97394,12 @@ var ts; /// /// /// +/// /// /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -93986,14 +97407,10 @@ var ts; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -94001,11 +97418,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -94215,15 +97632,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -94238,11 +97651,11 @@ var ts; if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -94257,7 +97670,6 @@ var ts; } var sourceFile = context.file; var ctorSymbol = getConstructorSymbol(context); - var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { @@ -94288,7 +97700,7 @@ var ts; return undefined; } // Because the preceding node could be touched, we need to insert nodes before delete nodes. - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { var deleteCallback = deletes_1[_i]; deleteCallback(); @@ -94453,6 +97865,488 @@ var ts; })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: actionName, + description: description, + actions: [ + { + description: description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182 /* CallExpression */: + return isAtTopLevelRequire(node); + case 180 /* PropertyAccessExpression */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228 /* VariableDeclarationList */: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227 /* VariableDeclaration */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228 /* VariableDeclarationList */) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 /* VariableStatement */ && varStatement.parent.kind === 269 /* SourceFile */; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249 /* ExternalModuleReference */: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + break; + } + case 182 /* CallExpression */: { + var call = parent; + if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 182 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + } + return false; + } + case 195 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 266 /* ShorthandPropertyAssignment */: + case 267 /* SpreadAssignment */: + return undefined; + case 265 /* PropertyAssignment */: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152 /* MethodDeclaration */: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84 /* ExportKeyword */)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 200 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 176 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + return parent.name !== node; + case 177 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -94461,14 +98355,9 @@ var ts; var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); /** * Compute the associated code actions * Exported for tests. @@ -94526,21 +98415,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); @@ -94559,7 +98448,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -94588,7 +98477,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -94649,6 +98538,14 @@ var ts; break; } } + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } if (ts.isReturnStatement(start) && !start.expression) { @@ -94875,7 +98772,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -95017,11 +98914,10 @@ var ts; case 153 /* Constructor */: return "constructor"; case 187 /* FunctionExpression */: - return scope.name - ? "function expression '" + scope.name.text + "'" - : "anonymous function expression"; case 229 /* FunctionDeclaration */: - return "function '" + scope.name.text + "'"; + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; case 188 /* ArrowFunction */: return "arrow function"; case 152 /* MethodDeclaration */: @@ -95078,7 +98974,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -95106,7 +99002,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -95132,13 +99028,10 @@ var ts; var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { - prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, - suffix: context.newLineCharacter - }); + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } var newNodes = []; // replace range with function call @@ -95177,7 +99070,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -95250,10 +99143,12 @@ var ts; newNodes.push(call); } } - var replacementRange = isReadonlyArray(range.range) - ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } - : { pos: range.range.getStart(), end: range.range.end }; - changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; @@ -95284,9 +99179,9 @@ var ts; var file = scope.getSourceFile(); var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); var isJS = ts.isInJavaScriptFile(scope); - var variableType = isJS + var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -95307,7 +99202,7 @@ var ts; // Declare var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } @@ -95320,8 +99215,8 @@ var ts; var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); if (oldVariableDeclaration) { // Declare - // CONSIDER: could detect that each is on a separate line - changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); @@ -95339,17 +99234,10 @@ var ts; // Declare var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); if (nodeToInsertBefore.pos === 0) { - // If we're at the beginning of the file, we need to take care not to insert before header comments - // (e.g. copyright, triple-slash references). Fortunately, this problem has already been solved - // for imports. - var insertionPos = ts.getSourceFileImportLocation(file); - changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { - prefix: insertionPos === 0 ? undefined : context.newLineCharacter, - suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter - }); + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); } else { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume if (node.parent.kind === 211 /* ExpressionStatement */) { @@ -95879,7 +99767,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); if (resolvedSymbol === symbol) { continue; } @@ -96019,15 +99907,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { // Then it will be available via `fixCannotFindModule`. @@ -96036,8 +99920,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -96092,13 +99976,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -96115,11 +99994,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -96177,6 +100056,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -96729,9 +100609,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = ts.getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; @@ -97016,8 +100896,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -97181,7 +101060,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -97191,10 +101070,11 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); }, @@ -97333,13 +101213,13 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -97427,10 +101307,10 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -97692,13 +101572,19 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function getCombinedCodeFix(scope, fixId, formatOptions) { + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); @@ -97815,7 +101701,7 @@ var ts; return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { - // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // @@ -97885,7 +101771,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -97942,6 +101827,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -97989,19 +101875,6 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257 /* JsxAttribute */: - case 259 /* JsxSpreadAttribute */: - case 265 /* PropertyAssignment */: - case 266 /* ShorthandPropertyAssignment */: - case 152 /* MethodDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - return true; - } - return false; - } /** * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } */ @@ -98011,11 +101884,11 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: if (node.parent.kind === 145 /* ComputedPropertyName */) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } @@ -98033,20 +101906,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_9 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_7.push(symbol); } }); - return result_9; + return result_7; } if (symbol) { - result_9.push(symbol); - return result_9; + result_7.push(symbol); + return result_7; } } return undefined; @@ -98283,8 +102156,8 @@ var ts; return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } // Set breakpoint on identifier element of destructuring pattern - // a or ...c or d: x from - // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || node.kind === 199 /* SpreadElement */ || node.kind === 265 /* PropertyAssignment */ || @@ -98426,8 +102299,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } @@ -99185,10 +103059,10 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = JSON.parse(options); + var localOptions = options === undefined ? undefined : JSON.parse(options); return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); }); }; @@ -99324,7 +103198,7 @@ var ts; var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { // for now treat files as JavaScript - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -99359,8 +103233,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 7b78c4237d632..c7c9d5c3d0a5e 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -453,6 +454,9 @@ declare namespace ts { interface JSDocContainer { } type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; + type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; + type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; + type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertySignature | PropertyDeclaration | PropertyAssignment | EnumMember; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -604,15 +608,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends NamedDeclaration { - propertyName?: PropertyName; - dotDotDotToken?: DotDotDotToken; - name: DeclarationName; - questionToken?: QuestionToken; - exclamationToken?: ExclamationToken; - type?: TypeNode; - initializer?: Expression; - } + type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -643,7 +639,7 @@ declare namespace ts { body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -660,30 +656,30 @@ declare namespace ts { } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassDeclaration | ClassExpression; + parent?: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; + parent?: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; + parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; } interface TypeNode extends Node { _typeNodeBrand: any; @@ -881,7 +877,7 @@ declare namespace ts { type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; - type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; @@ -905,6 +901,7 @@ declare namespace ts { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; + name: never; } interface LiteralLikeNode extends Node { text: string; @@ -1279,7 +1276,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassDeclaration | ClassExpression; + parent?: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1366,6 +1363,7 @@ declare namespace ts { interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; parent?: SourceFile | ModuleBlock; + /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier?: Expression; @@ -1620,7 +1618,7 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. @@ -1731,6 +1729,16 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -1750,7 +1758,8 @@ declare namespace ts { getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; /** * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead * This will be removed in a future version. @@ -1790,33 +1799,79 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, SuppressAnyReturnType = 256, WriteTypeParametersInQualifiedName = 512, - AllowThisInObjectLiteral = 1024, - AllowQualifedNameInPlaceOfIdentifier = 2048, - AllowAnonymousIdentifier = 8192, - AllowEmptyUnionOrIntersection = 16384, - AllowEmptyTuple = 32768, - IgnoreErrors = 60416, - InObjectTypeLiteral = 1048576, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + IgnoreErrors = 3112960, + InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + SuppressAnyReturnType = 256, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, + InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469295, + } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + } + /** + * @deprecated + */ interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; - buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - interface SymbolWriter { + /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; + /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + } + /** + * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString + */ + interface SymbolWriter extends SymbolTracker { writeKeyword(text: string): void; writeOperator(text: string): void; writePunctuation(text: string): void; @@ -1829,34 +1884,6 @@ declare namespace ts { increaseIndent(): void; decreaseIndent(): void; clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError(): void; - reportPrivateInBaseOfClassExpression(propertyName: string): void; - reportInaccessibleUniqueSymbolError(): void; - } - enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 4, - NoTruncation = 8, - WriteArrowStyleSignature = 16, - WriteOwnNameForAnyLike = 32, - WriteTypeArgumentsOfSignature = 64, - InElementType = 128, - UseFullyQualifiedType = 256, - InFirstTypeArgument = 512, - InTypeAlias = 1024, - SuppressAnyReturnType = 4096, - AddUndefined = 8192, - WriteClassExpressionAsTypeLiteral = 16384, - InArrayType = 32768, - UseAliasDefinedOutsideCurrentScope = 65536, - AllowUniqueESSymbolType = 131072, - } - enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, } enum TypePredicateKind { This = 0, @@ -2071,6 +2098,7 @@ declare namespace ts { EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, ContainsSpread = 1024, + ReverseMapped = 2048, ClassOrInterface = 3, } interface ObjectType extends Type { @@ -2150,15 +2178,14 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - Contravariant = 1, - NakedTypeVariable = 2, - MappedType = 4, - ReturnType = 8, - NeverType = 16, + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, } interface InferenceInfo { typeParameter: TypeParameter; candidates: Type[]; + contraCandidates: Type[]; inferredType: Type; priority: InferencePriority; topLevel: boolean; @@ -2299,6 +2326,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -2472,12 +2500,13 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; + createHash?(data: string): string; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2634,6 +2663,10 @@ declare namespace ts { * collisions. */ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -2689,6 +2722,13 @@ declare namespace ts { interface PrinterOptions { removeComments?: boolean; newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + } + interface SymbolTracker { + trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + reportInaccessibleThisError?(): void; + reportPrivateInBaseOfClassExpression?(propertyName: string): void; + reportInaccessibleUniqueSymbolError?(): void; } interface TextSpan { start: number; @@ -2701,6 +2741,71 @@ declare namespace ts { interface SyntaxList extends Node { _children: Node[]; } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + DelimitersMask = 28, + AllowTrailingComma = 32, + Indented = 64, + SpaceBetweenBraces = 128, + SpaceBetweenSiblings = 256, + Braces = 512, + Parenthesis = 1024, + AngleBrackets = 2048, + SquareBrackets = 4096, + BracketsMask = 7680, + OptionalIfUndefined = 8192, + OptionalIfEmpty = 16384, + Optional = 24576, + PreferNewLine = 32768, + NoTrailingNewLine = 65536, + NoInterveningComments = 131072, + NoSpaceIfEmpty = 262144, + SingleElement = 524288, + Modifiers = 131328, + HeritageClauses = 256, + SingleLineTypeLiteralMembers = 448, + MultiLineTypeLiteralMembers = 65, + TupleTypeElements = 336, + UnionTypeConstituents = 260, + IntersectionTypeConstituents = 264, + ObjectBindingPatternElements = 262576, + ArrayBindingPatternElements = 262448, + ObjectLiteralExpressionProperties = 263122, + ArrayLiteralExpressionElements = 4466, + CommaListElements = 272, + CallExpressionArguments = 1296, + NewExpressionArguments = 9488, + TemplateExpressionSpans = 131072, + SingleLineBlockStatements = 384, + MultiLineBlockStatements = 65, + VariableDeclarationList = 272, + SingleLineFunctionBodyStatements = 384, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 256, + ClassMembers = 65, + InterfaceMembers = 65, + EnumMembers = 81, + CaseBlockClauses = 65, + NamedImportsOrExportsElements = 432, + JsxElementOrFragmentChildren = 131072, + JsxElementAttributes = 131328, + CaseOrDefaultClauseStatements = 81985, + HeritageClauseTypes = 272, + SourceFileStatements = 65537, + Decorators = 24577, + TypeArguments = 26896, + TypeParameters = 26896, + Parameters = 1296, + IndexSignatureParameters = 4432, + } } declare namespace ts { const versionMajorMinor = "2.7"; @@ -2725,26 +2830,14 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - /** - * Partial interface of the System thats needed to support the caching of directory structure - */ - interface DirectoryStructureHost { + interface System { + args: string[]; newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - exit(exitCode?: number): void; - } - interface System extends DirectoryStructureHost { - args: string[]; getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2752,7 +2845,13 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2760,9 +2859,11 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; + exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; + clearScreen?(): void; } interface FileWatcher { close(): void; @@ -2791,7 +2892,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -2811,8 +2912,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; @@ -2968,7 +3071,7 @@ declare namespace ts { function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; - function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; @@ -3160,6 +3263,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -3235,13 +3339,13 @@ declare namespace ts { declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ - function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral; + function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; - function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; + function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -3710,18 +3814,7 @@ declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } declare namespace ts { - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } -} -declare namespace ts { - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -3749,6 +3842,258 @@ declare namespace ts { */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} +declare namespace ts { + type AffectedFileResult = { + result: T; + affected: SourceFile | Program; + } | undefined; + interface BuilderProgramHost { + /** + * return true if file names are treated with case sensitivity + */ + useCaseSensitiveFileNames(): boolean; + /** + * If provided this would be used this hash instead of actual file shape text for detecting changes + */ + createHash?: (data: string) => string; + /** + * When emit or emitNextAffectedFile are called without writeFile, + * this callback if present would be used to write files + */ + writeFile?: WriteFileCallback; + } + /** + * Builder to manage the program state changes + */ + interface BuilderProgram { + /** + * Returns current program + */ + getProgram(): Program; + /** + * Get compiler options of the program + */ + getCompilerOptions(): CompilerOptions; + /** + * Get the source file in the program with file name + */ + getSourceFile(fileName: string): SourceFile | undefined; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Get the diagnostics for compiler options + */ + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics that dont belong to any file + */ + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the syntax diagnostics, for all source files if source file is not supplied + */ + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get all the dependencies of the file + */ + getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + /** + * Get the current directory of the program + */ + getCurrentDirectory(): string; + } + /** + * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files + */ + interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Gets the semantic diagnostics from the program for the next affected file and caches it + * Returns undefined if the iteration is complete + */ + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + } + /** + * The builder that can handle the changes in program and iterate through changed file to emit the files + * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files + */ + interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; + } + /** + * Create the builder to manage semantic diagnostics and cache them + */ + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + /** + * Create the builder that can handle the changes in program and iterate through changed files + * to emit the those files and manage semantic diagnostics cache as well + */ + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + /** + * Creates a builder thats just abstraction over program and can be used with watch + */ + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram): BuilderProgram; +} +declare namespace ts { + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string) => void; + type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; + interface WatchCompilerHost { + /** + * Used to create the program when need for program creation or recreation detected + */ + createProgram: CreateProgram; + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string): void; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + createHash?(data: string): string; + /** + * Use to check file presence for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + fileExists(path: string): boolean; + /** + * Use to read file text for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + readFile(path: string, encoding?: string): string | undefined; + /** If provided, used for module resolution as well as to handle directory structure */ + directoryExists?(path: string): boolean; + /** If provided, used in resolutions as well as handling directory structure */ + getDirectories?(path: string): string[]; + /** If provided, used to cache and handle directory structure modifications */ + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + /** Symbol links resolution */ + realpath?(path: string): string; + /** If provided would be used to write log about compilation */ + trace?(s: string): void; + /** If provided is used to get the environment variable */ + getEnvironmentVariable?(name: string): string; + /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + /** + * Host to create watch with root files and options + */ + interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { + /** root files to use to generate program */ + rootFiles: string[]; + /** Compiler options */ + options: CompilerOptions; + } + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports the diagnostics in reading/writing or parsing of the config file + */ + onConfigFileDiagnostic: DiagnosticReporter; + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Host to create watch with config file + */ + interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { + /** Name of the config file to compile */ + configFileName: string; + /** Options to extend */ + optionsToExtend?: CompilerOptions; + /** + * Used to generate source file names from the config file and its include, exclude, files rules + * and also to cache the directory stucture + */ + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + } + interface Watch { + /** Synchronize with host and get updated program */ + getProgram(): T; + } + /** + * Creates the watch what generates program using the config file + */ + interface WatchOfConfigFile extends Watch { + } + /** + * Creates the watch that generates program using the root files and compiler options + */ + interface WatchOfFilesAndCompilerOptions extends Watch { + /** Updates the root files in the program, only if this is not config file compilation */ + updateRootFileNames(fileNames: string[]): void; + } + /** + * Create the watch compiler host for either configFile or fileNames and its options + */ + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + /** + * Creates the watch from the host for root files and compiler options + */ + function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for config file + */ + function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; +} declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; /** @@ -3924,6 +4269,7 @@ declare namespace ts { useCaseSensitiveFileNames?(): boolean; readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; + realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; @@ -3982,7 +4328,8 @@ declare namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; 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[]; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -3998,8 +4345,13 @@ declare namespace ts { getProgram(): Program; dispose(): void; } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4074,6 +4426,17 @@ declare namespace ts { */ commands?: CodeActionCommand[]; } + interface CodeFixAction extends CodeAction { + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands: ReadonlyArray | undefined; + } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } @@ -4210,6 +4573,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4227,6 +4591,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4342,6 +4707,7 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: string; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -4508,6 +4874,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", + optionalModifier = "optional", } enum ClassificationTypeNames { comment = "comment", @@ -4653,9 +5020,6 @@ declare namespace ts { declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.7"; - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 1fbae487f8038..b4f8d26c1fab5 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -489,14 +489,19 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; (function (TokenFlags) { @@ -510,8 +515,9 @@ var ts; TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier"; TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier"; TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier"; + TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; - TokenFlags[TokenFlags["NumericLiteralFlags"] = 496] = "NumericLiteralFlags"; + TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; (function (FlowFlags) { @@ -556,47 +562,77 @@ var ts; // Diagnostics were produced and outputs were generated in spite of them. ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); + /* @internal */ + var UnionReduction; + (function (UnionReduction) { + UnionReduction[UnionReduction["None"] = 0] = "None"; + UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; + UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; + })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // empty space NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; + NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; // Error handling - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; + NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; + NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; // State - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; + TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; // even though `T` can't be accessed in the current scope. - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -604,12 +640,14 @@ var ts; // Write symbols's type argument if it is instantiated symbol // eg. class C { p: T } <-- Show p as C.p here // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -745,6 +783,7 @@ var ts; CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Late"] = 1024] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -871,6 +910,7 @@ var ts; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ @@ -894,11 +934,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1181,6 +1219,8 @@ var ts; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -1198,20 +1238,22 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; // Masks // - Additional bitmasks TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; @@ -1248,6 +1290,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1294,6 +1337,78 @@ var ts; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; + ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; + ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; + ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; + ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; + ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + ListFormat[ListFormat["Braces"] = 512] = "Braces"; + ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; + ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; + ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; + ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; + ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; + ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; + ListFormat[ListFormat["Optional"] = 24576] = "Optional"; + // Other + ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; + ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; + ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; + ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; + ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; + ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; + ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; + ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; + ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; + ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; + ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; + ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; + ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; + ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; + ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; + ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; + ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; + ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; + ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; + ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; + ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; + ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; + ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; + ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments"; + ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters"; + ListFormat[ListFormat["Parameters"] = 1296] = "Parameters"; + ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; + })(ListFormat = ts.ListFormat || (ts.ListFormat = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1396,7 +1511,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1409,6 +1524,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -1552,6 +1668,9 @@ var ts; ts.forEach = forEach; /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -1561,6 +1680,19 @@ var ts; return undefined; } ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -1577,13 +1709,27 @@ var ts; ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { var result = []; - Debug.assert(arrayA.length === arrayB.length); + Debug.assertEqual(arrayA.length, arrayB.length); for (var i = 0; i < arrayA.length; i++) { result.push(callback(arrayA[i], arrayB[i], i)); } return result; } ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; function zipToMap(keys, values) { Debug.assert(keys.length === values.length); var map = createMap(); @@ -1666,17 +1812,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -1748,11 +1883,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -1824,25 +1960,33 @@ var ts; return result; } ts.flatMap = flatMap; - function flatMapIter(iter, mapfn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapfn(value); - if (res) { - if (isArray(res)) { - result.push.apply(result, res); - } - else { - result.push(res); + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); } - } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; } - return result; } - ts.flatMapIter = flatMapIter; + ts.flatMapIterator = flatMapIterator; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1865,12 +2009,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -1879,20 +2034,35 @@ var ts; return result; } ts.mapDefined = mapDefined; - function mapDefinedIter(iter, mapFn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapFn(value); - if (res !== undefined) { - result.push(res); + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } } - } - return result; + }; } - ts.mapDefinedIter = mapDefinedIter; + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -2158,7 +2328,7 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // Note: we need the following type assertion because of GH #17069 + // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2665,6 +2835,9 @@ var ts; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -3069,7 +3242,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */) + if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) return 3; } // Per RFC 1738 'file' URI schema has the shape file:/// @@ -3149,11 +3322,6 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ - function moduleHasNonRelativeName(moduleName) { - return !ts.isExternalModuleNameRelative(moduleName); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -3176,7 +3344,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3236,7 +3406,7 @@ var ts; ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part @@ -3266,7 +3436,7 @@ var ts; } else { // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" + // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + ts.directorySeparator]; @@ -3285,7 +3455,7 @@ var ts; var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } // Find the component that differs @@ -3507,7 +3677,6 @@ var ts; function getSubPatternFromSpec(spec, basePath, usage, _a) { var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; - var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); var lastComponent = lastOrUndefined(components); @@ -3524,11 +3693,7 @@ var ts; for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { var component = components_1[_i]; if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - return undefined; - } subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; } else { if (usage === "directories") { @@ -3854,10 +4019,10 @@ var ts; } function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0 /* None */; this.modifierFlagsCache = 0 /* None */; this.transformFlags = 0 /* None */; @@ -3997,9 +4162,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; /** @@ -4118,182 +4281,20 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - /** - * If the readDirectory result was already cached, it returns that - * Otherwise gets result from host and caches it. - * The host request is done under try catch block to avoid caching incorrect result - */ - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - // If there is exception to read directories, dont cache the result and direct the calls to host - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - // Just clear the cache for now - // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated - clearCache(); - } - else { - // This was earlier a file (hence not in cached directory contents) - // or we never cached the directory containing it - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - // Folder added or removed, clear the cache instead of updating the folder and its structure - clearCache(); - } - else { - // No need to update the directory structure, just files - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.singleElementArray = singleElementArray; })(ts || (ts = {})); /// var ts; @@ -4568,7 +4569,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -4601,6 +4602,9 @@ var ts; return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); } var nodeSystem = { + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -4685,7 +4689,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -5022,6 +5031,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5136,6 +5147,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -5190,7 +5202,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -5278,6 +5290,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5356,6 +5369,10 @@ var ts; Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5442,7 +5459,6 @@ var ts; The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), @@ -5493,6 +5509,7 @@ var ts; Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), @@ -5533,7 +5550,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -5640,6 +5657,9 @@ var ts; Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5668,6 +5688,9 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5743,9 +5766,9 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -5757,6 +5780,9 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); /// @@ -5904,7 +5930,7 @@ var ts; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: - Can contain Unicode 3.0.0 categories: + Can contain Unicode 3.0.0 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5912,7 +5938,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: = - Can contain IdentifierStart + Unicode 3.0.0 categories: + Can contain IdentifierStart + Unicode 3.0.0 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), or @@ -5926,7 +5952,7 @@ var ts; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers IdentifierStart :: - Can contain Unicode 6.2 categories: + Can contain Unicode 6.2 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5934,7 +5960,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: - Can contain IdentifierStart + Unicode 6.2 categories: + Can contain IdentifierStart + Unicode 6.2 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), @@ -6253,7 +6279,7 @@ var ts; } function scanConflictMarkerTrivia(text, pos, error) { if (error) { - error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); } var ch = text.charCodeAt(pos); var len = text.length; @@ -6509,19 +6535,60 @@ var ts; lookAhead: lookAhead, scanRange: scanRange, }; - function error(message, length) { + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } if (onError) { + var oldPos = pos; + pos = errPos; onError(message, length || 0); + pos = oldPos; } } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } function scanNumber() { var start = pos; - while (isDigit(text.charCodeAt(pos))) - pos++; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; if (text.charCodeAt(pos) === 46 /* dot */) { pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; + decimalFragment = scanNumberFragment(); } var end = pos; if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { @@ -6529,17 +6596,29 @@ var ts; tokenFlags |= 16 /* Scientific */; if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) pos++; - if (isDigit(text.charCodeAt(pos))) { - pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; - end = pos; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); } else { - error(ts.Diagnostics.Digit_expected); + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; } } - return "" + +(text.substring(start, end)); + if (tokenFlags & 512 /* ContainsSeparator */) { + var result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; + } + return "" + +result; + } + else { + return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + } } function scanOctalDigits() { var start = pos; @@ -6552,21 +6631,39 @@ var ts; * Scans the given number of hexadecimal digits in the text, * returning -1 if the given number is unavailable. */ - function scanExactNumberOfHexDigits(count) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); } /** * Scans as many hexadecimal digits as are available in the text, * returning -1 if the given number of digits was unavailable. */ - function scanMinimumNumberOfHexDigits(count) { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true); + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } - function scanHexDigits(minCount, scanAsManyAsPossible) { + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { var digits = 0; var value = 0; + var allowSeparator = false; + var isPreviousTokenSeparator = false; while (digits < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { value = value * 16 + ch - 48 /* _0 */; } @@ -6581,10 +6678,14 @@ var ts; } pos++; digits++; + isPreviousTokenSeparator = false; } if (digits < minCount) { value = -1; } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return value; } function scanString(jsxAttributeString) { @@ -6735,7 +6836,7 @@ var ts; } } function scanHexadecimalEscape(numDigits) { - var escapedValue = scanExactNumberOfHexDigits(numDigits); + var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); } @@ -6745,7 +6846,7 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1); + var escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); var isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -6789,7 +6890,7 @@ var ts; if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { var start_1 = pos; pos += 2; - var value = scanExactNumberOfHexDigits(4); + var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false); pos = start_1; return value; } @@ -6841,8 +6942,27 @@ var ts; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. var numberOfDigits = 0; + var separatorAllowed = false; + var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); + // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + if (ch === 95 /* _ */) { + tokenFlags |= 512 /* ContainsSeparator */; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; var valueOfCh = ch - 48 /* _0 */; if (!isDigit(ch) || valueOfCh >= base) { break; @@ -6850,11 +6970,17 @@ var ts; value = value * base + valueOfCh; pos++; numberOfDigits++; + isPreviousTokenSeparator = false; } // Invalid binaryIntegerLiteral or octalIntegerLiteral if (numberOfDigits === 0) { return -1; } + if (text.charCodeAt(pos - 1) === 95 /* _ */) { + // Literal ends with underscore - not allowed + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + return value; + } return value; } function scan() { @@ -7044,7 +7170,7 @@ var ts; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1); + var value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); if (value < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -7390,7 +7516,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -7413,6 +7539,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: @@ -7423,55 +7550,30 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - pos++; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - pos++; return token = 39 /* AsteriskToken */; case 123 /* openBrace */: - pos++; return token = 17 /* OpenBraceToken */; case 125 /* closeBrace */: - pos++; return token = 18 /* CloseBraceToken */; case 91 /* openBracket */: - pos++; return token = 21 /* OpenBracketToken */; case 93 /* closeBracket */: - pos++; return token = 22 /* CloseBracketToken */; case 60 /* lessThan */: - pos++; return token = 27 /* LessThanToken */; - case 62 /* greaterThan */: - pos++; - return token = 29 /* GreaterThanToken */; case 61 /* equals */: - pos++; return token = 58 /* EqualsToken */; case 44 /* comma */: - pos++; return token = 26 /* CommaToken */; case 46 /* dot */: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24 /* DotDotDotToken */; - } return token = 23 /* DotToken */; - case 33 /* exclamation */: - pos++; - return token = 51 /* ExclamationToken */; - case 63 /* question */: - pos++; - return token = 55 /* QuestionToken */; } if (isIdentifierStart(ch, 6 /* Latest */)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } @@ -7479,7 +7581,7 @@ var ts; return token = 71 /* Identifier */; } else { - return pos += 1, token = 0 /* Unknown */; + return token = 0 /* Unknown */; } } function speculationHelper(callback, isLookahead) { @@ -7560,8 +7662,9 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.emptyArray = []; + ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -7581,15 +7684,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str += " "; }, @@ -7603,10 +7715,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -7640,12 +7752,19 @@ var ts; return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -7866,7 +7985,7 @@ var ts; function getLiteralText(node, sourceFile) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent) { + if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; @@ -8306,7 +8425,7 @@ var ts; return node === parent.type; case 182 /* CallExpression */: case 183 /* NewExpression */: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -8892,11 +9011,6 @@ var ts; (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")'). - * This function does not test if the node is in a JavaScript file or not. - */ function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 182 /* CallExpression */) { return false; @@ -9055,41 +9169,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 /* ModuleDeclaration */ && node.body && node.body.kind === 234 /* ModuleDeclaration */ && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -9120,7 +9223,7 @@ var ts; if (node.kind === 147 /* Parameter */) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -9230,6 +9333,33 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208 /* Block */: + case 209 /* VariableStatement */: + case 221 /* WithStatement */: + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -9579,6 +9709,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; /** * Includes the word "Symbol" with unicode escapes */ @@ -10011,7 +10145,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -10206,7 +10352,7 @@ var ts; * parsed in a JavaScript file, gets the type annotation from JSDoc. */ function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (node.type) { + if (ts.hasType(node)) { return node.type; } if (checkJSDoc || isInJavaScriptFile(node)) { @@ -10651,14 +10797,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -11021,6 +11167,10 @@ var ts; return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11227,8 +11377,8 @@ var ts; // // { // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; @@ -11879,7 +12029,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192 /* AwaitExpression */; + return node.kind === 190 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -12352,7 +12502,7 @@ var ts; /* @internal */ function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; // Keywords @@ -12466,6 +12616,18 @@ var ts; return node && (node.kind === 154 /* GetAccessor */ || node.kind === 155 /* SetAccessor */); } ts.isAccessor = isAccessor; + /* @internal */ + function isMethodOrAccessor(node) { + switch (node.kind) { + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; // Type members function isTypeElement(node) { var kind = node.kind; @@ -13020,6 +13182,39 @@ var ts; return !!node.jsDoc && node.jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; + /** True if has type node attached to it. */ + /* @internal */ + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + /** True if has initializer node attached to it. */ + /* @internal */ + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); /// /// @@ -13109,20 +13304,48 @@ var ts; case 267 /* SpreadAssignment */: return visitNode(cbNode, node.expression); case 147 /* Parameter */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 150 /* PropertyDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 149 /* PropertySignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 265 /* PropertyAssignment */: - case 227 /* VariableDeclaration */: - case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 227 /* VariableDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); + case 177 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 161 /* FunctionType */: case 162 /* ConstructorType */: case 156 /* CallSignature */: @@ -13572,7 +13795,7 @@ var ts; // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost // all nodes would need extra state on them to store this info. // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 // grammar specification. // // An important thing about these context concepts. By default they are effectively inherited @@ -13750,15 +13973,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -14295,9 +14510,13 @@ var ts; return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); case 18 /* TypeParameters */: return isIdentifier(); - case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + if (token() === 26 /* CommaToken */) { + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 19 /* TypeArguments */: @@ -14317,7 +14536,7 @@ var ts; function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not + // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // // extends {} { @@ -14401,7 +14620,7 @@ var ts; } function isVariableDeclaratorListTerminator() { // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } @@ -14506,6 +14725,10 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -14904,7 +15127,7 @@ var ts; // We also do not need to check for negatives because any prefix operator would be part of a // parent unary expression. if (node.kind === 8 /* NumericLiteral */) { - node.numericLiteralFlags = scanner.getTokenFlags() & 496 /* NumericLiteralFlags */; + node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; } nextToken(); finishNode(node); @@ -15014,7 +15237,7 @@ var ts; // // // - // We do *not* want to consume the > as we're consuming the expression for "". + // We do *not* want to consume the `>` as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } @@ -15754,7 +15977,7 @@ var ts; // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". // // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { @@ -15781,7 +16004,7 @@ var ts; // we're in '2' or '3'. Consume the assignment and return. // // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= + // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } @@ -15912,7 +16135,7 @@ var ts; var second = nextToken(); if (first === 19 /* OpenParenToken */) { if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". + // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. @@ -16113,7 +16336,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -16475,7 +16700,8 @@ var ts; // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" // For example: // var foo3 = require("subfolder - // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; expression = parseTokenNode(); } @@ -16523,7 +16749,7 @@ var ts; // treated as the invocation of "new Foo". We disambiguate that in code (to match // the original grammar) by making sure that if we see an ObjectCreationExpression // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think + // object creation only, and not at all as an invocation. Another way to think // about this is that for every "new" that we see, we will consume an argument list if // it is there as part of the *associated* object creation node. Any additional // argument lists we see, will become invocation expressions. @@ -16887,7 +17113,7 @@ var ts; } var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. + // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } // If we have a '<', then only parse this as a argument list if the type arguments @@ -17801,8 +18027,8 @@ var ts; // off. The grammar would look something like this: // // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. node.initializer = ts.hasModifier(node, 32 /* Static */) @@ -17884,6 +18110,7 @@ var ts; switch (token()) { case 19 /* OpenParenToken */: // Method declaration case 27 /* LessThanToken */: // Generic Method declaration + case 51 /* ExclamationToken */: // Non-null assertion on property name case 56 /* ColonToken */: // Type Annotation for declaration case 58 /* EqualsToken */: // Initializer for declaration case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on. @@ -18563,7 +18790,6 @@ var ts; scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. - var advanceToken = true; var state = 1 /* SawAsterisk */; var margin = undefined; // + 4 for leading '/** ' @@ -18575,17 +18801,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5 /* WhitespaceTrivia */) { + t = nextJSDocToken(); } - if (token() === 4 /* NewLineTrivia */) { + if (t === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + loop: while (true) { + switch (t) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); @@ -18594,7 +18820,6 @@ var ts; // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` state = 0 /* BeginningOfLine */; - advanceToken = false; margin = undefined; indent++; } @@ -18639,19 +18864,14 @@ var ts; indent += whitespace.length; break; case 1 /* EndOfFileToken */: - break; + break loop; default: // anything other than whitespace or asterisk at the beginning of the line starts the comment text state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -18736,7 +18956,8 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -18749,8 +18970,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { state = 0 /* BeginningOfLine */; @@ -18759,8 +18981,11 @@ var ts; indent = 0; break; case 57 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through + case 1 /* EndOfFileToken */: // Done - break; + break loop; case 5 /* WhitespaceTrivia */: if (state === 2 /* SavingComments */) { pushComment(scanner.getTokenText()); @@ -18778,7 +19003,7 @@ var ts; if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; + indent += 1; break; } // record the * as a comment @@ -18788,15 +19013,11 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281 /* JSDocTag */, atToken.pos); @@ -18804,8 +19025,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -18876,10 +19096,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280 /* JSDocTypeLiteral */, start_2); @@ -18985,10 +19202,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -19033,8 +19247,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); @@ -19074,34 +19287,44 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0 /* Property */; + break; case "arg": case "argument": case "param": - return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1 /* Parameter */; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146 /* TypeParameter */); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -19120,6 +19343,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17 /* OpenBraceToken */); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -19298,7 +19529,7 @@ var ts; // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have + // depend if delta is positive or negative. If delta is positive then we have // something like: // // -------------------AAA----------------- @@ -19322,7 +19553,7 @@ var ts; element.pos = Math.min(element.pos, changeRangeNewEnd); // If the 'end' is after the change range, then we always adjust it by the delta // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we + // will depend on if delta is positive or negative. If delta is positive then we // have something like: // // -------------------AAA----------------- @@ -19908,7 +20139,7 @@ var ts; // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -20331,7 +20562,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 /* StringLiteral */ || expr2.kind === 13 /* NoSubstitutionTemplateLiteral */); + } + function isNarrowableInOperands(left, right) { + return (left.kind === 9 /* StringLiteral */ || left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -20345,6 +20579,8 @@ var ts; isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); case 93 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); + case 92 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); case 26 /* CommaToken */: return isNarrowingExpression(expr.right); } @@ -21136,7 +21372,7 @@ var ts; // to the one we would get for: { <...>(...): T } // // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072 /* Signature */); @@ -21724,27 +21960,13 @@ var ts; setCommonJsModuleIndicator(node); declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - var symbol = lookupSymbolForName(node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); - } function bindModuleExportsAssignment(node) { // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' // is still pointing to 'module.exports'. // We do not want to consider this as 'export=' since a module can have only one of these. // Similarly we do not want to treat 'module.exports = exports' as an 'export='. var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { // Mark it as a module in case there are no other exports in the file setCommonJsModuleIndicator(node); return; @@ -21815,7 +22037,7 @@ var ts; if (node.kind === 195 /* BinaryExpression */) { leftSideOfAssignment.parent = node; } - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + if (container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, target)) { // This can be an alias for the 'exports' or 'module.exports' names, e.g. // var util = module.exports; // util.property = function ... @@ -21827,11 +22049,7 @@ var ts; } } function lookupSymbolForName(name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + return lookupSymbolForNameWorker(container, name); } function bindPropertyAssignment(functionName, propertyAccess, isPrototypeProperty) { var symbol = lookupSymbolForName(functionName); @@ -21947,7 +22165,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); @@ -22041,6 +22259,29 @@ var ts; return true; } } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } /** * Computes the transform flags for a node, given the transform flags of its subtree * @@ -22101,6 +22342,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); + case 181 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -22109,15 +22352,19 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; @@ -22128,19 +22375,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 180 /* PropertyAccessExpression */: - case 181 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22153,7 +22388,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22174,7 +22409,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22203,7 +22438,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; + return transformFlags & ~939525441 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22223,7 +22458,7 @@ var ts; transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -22249,7 +22484,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. @@ -22266,7 +22501,7 @@ var ts; transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22284,7 +22519,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22295,7 +22530,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -22307,7 +22542,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22321,7 +22556,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -22348,7 +22583,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22366,7 +22601,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -22377,7 +22612,7 @@ var ts; transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -22421,7 +22656,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22453,7 +22688,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -22478,19 +22713,31 @@ var ts; transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22504,7 +22751,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -22520,7 +22767,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22530,7 +22777,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22539,7 +22786,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22550,7 +22797,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -22559,7 +22806,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; + return transformFlags & ~977327425 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -22571,18 +22818,25 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; + var excludeFlags = 939525441 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: @@ -22591,8 +22845,6 @@ var ts; case 76 /* ConstKeyword */: case 233 /* EnumDeclaration */: case 268 /* EnumMember */: - case 185 /* TypeAssertionExpression */: - case 203 /* AsExpression */: case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. @@ -22709,7 +22961,8 @@ var ts; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. @@ -22720,11 +22973,11 @@ var ts; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; @@ -22737,7 +22990,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; case 179 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; + excludeFlags = 942740801 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. @@ -22756,7 +23009,7 @@ var ts; break; case 178 /* ArrayLiteralExpression */: case 183 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. @@ -22802,27 +23055,27 @@ var ts; case 182 /* CallExpression */: case 183 /* NewExpression */: case 178 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; case 234 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; + return 977327425 /* ModuleExcludes */; case 147 /* Parameter */: - return 536872257 /* ParameterExcludes */; + return 939525441 /* ParameterExcludes */; case 188 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; + return 1003902273 /* ArrowFunctionExcludes */; case 187 /* FunctionExpression */: case 229 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; + return 1003935041 /* FunctionExcludes */; case 228 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; + return 948962625 /* VariableDeclarationListExcludes */; case 230 /* ClassDeclaration */: case 200 /* ClassExpression */: - return 539358529 /* ClassExcludes */; + return 942011713 /* ClassExcludes */; case 153 /* Constructor */: - return 601015617 /* ConstructorExcludes */; + return 1003668801 /* ConstructorExcludes */; case 152 /* MethodDeclaration */: case 154 /* GetAccessor */: case 155 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; + return 1003668801 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: case 130 /* NeverKeyword */: @@ -22841,14 +23094,23 @@ var ts; case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 179 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; + return 942740801 /* ObjectLiteralExcludes */; case 264 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; + return 940574017 /* CatchClauseExcludes */; case 175 /* ObjectBindingPattern */: case 176 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; + return 940049729 /* BindingPatternExcludes */; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + case 186 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; default: - return 536872257 /* NodeExcludes */; + return 939525441 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -22864,7 +23126,7 @@ var ts; /** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } @@ -22960,8 +23222,9 @@ var ts; visitType(type.modifiersType); } function visitSignature(signature) { - if (signature.typePredicate) { - visitType(signature.typePredicate.type); + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); } ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { @@ -23067,9 +23330,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -23623,8 +23886,8 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { @@ -23641,11 +23904,17 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - if (!compilerOptions.preserveSymlinks) { - resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + var originalPath = void 0; + if (!compilerOptions.preserveSymlinks && resolvedValue) { + originalPath = resolvedValue.path; + var path = realPath(resolved_1.value.path, host, traceEnabled); + if (path === originalPath) { + originalPath = undefined; + } + resolvedValue = __assign({}, resolvedValue, { path: path }); } // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -23681,7 +23950,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -23695,6 +23966,49 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + */ + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts" /* Dts */; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } /* @internal */ function directoryProbablyExists(directoryName, host) { // if host does not support 'directoryExists' assume that directory will exist @@ -23780,18 +24094,41 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { - var host = _a.host, traceEnabled = _a.traceEnabled; + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); + if (subModuleName === "") { + var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + } + else { + var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); + if (typeof jsPath === "string") { + subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { + subModuleName = addExtensionAndIndex(subModuleName); + } var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -23949,13 +24286,18 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + /* @internal */ + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -23971,7 +24313,8 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + // No originalPath because classic resolution doesn't resolve realPath + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*originalPath*/ undefined, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { @@ -24016,7 +24359,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*originalPath*/ undefined, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -24146,6 +24489,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -24179,16 +24527,32 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { node = ts.getParseTreeNode(node, ts.isExpression); return node ? getContextualType(node) : undefined; }, + isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { node = ts.getParseTreeNode(node, ts.isCallLikeExpression); @@ -24203,7 +24567,11 @@ var ts; }, isValidPropertyAccess: function (node, propertyName) { node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); + }, + isValidPropertyAccessForCompletions: function (node, type, property) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + return !!node && isValidPropertyAccessForCompletions(node, type, property); }, getSignatureFromDeclaration: function (declaration) { declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); @@ -24227,7 +24595,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); @@ -24269,11 +24637,17 @@ var ts; getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, - resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + resolveName: function (name, location, meaning, excludeGlobals) { + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -24319,13 +24693,15 @@ var ts; var markerSubType = createType(32768 /* TypeParameter */); markerSubType.constraint = markerSuperType; var markerOtherType = createType(32768 /* TypeParameter */); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var reverseMappedCache = ts.createMap(); var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -24492,20 +24868,20 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - var _displayBuilder; var TypeSystemPropertyName; (function (TypeSystemPropertyName) { TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { CheckMode[CheckMode["Normal"] = 0] = "Normal"; CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; + CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; })(CheckMode || (CheckMode = {})); var CallbackCheck; (function (CallbackCheck) { @@ -24535,6 +24911,142 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + /** + * @deprecated + */ + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -24550,10 +25062,12 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -24812,7 +25326,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage @@ -24900,10 +25414,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { + if (excludeGlobals === void 0) { excludeGlobals = false; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -24963,7 +25478,7 @@ var ts; if (location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. - if (result = moduleExports.get("default")) { + if (result = moduleExports.get("default" /* Default */)) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { break loop; @@ -25119,14 +25634,14 @@ var ts; } break; } - if (location.kind !== 208 /* Block */) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. - // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // If `result === lastNonBlockLocation.symbol`, that means that we are somewhere inside `lastNonBlockLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; @@ -25138,7 +25653,9 @@ var ts; return lastLocation.symbol; } } - result = lookup(globals, name, meaning); + if (!excludeGlobals) { + result = lookup(globals, name, meaning); + } } if (!result) { if (nameNotFoundMessage) { @@ -25201,6 +25718,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -25369,6 +25900,41 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a default member specified + if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -25377,15 +25943,15 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -25465,7 +26031,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } var symbol = symbolFromModule && symbolFromVariable ? @@ -25717,7 +26283,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -25752,8 +26318,42 @@ var ts; // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -25806,7 +26406,7 @@ var ts; if (!source) return; source.forEach(function (sourceSymbol, id) { - if (id === "default") + if (id === "default" /* Default */) return; var targetSymbol = target.get(id); if (!targetSymbol) { @@ -25991,11 +26591,14 @@ var ts; } var visitedSymbolTables = []; return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols) { + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols); + var result = trySymbolTable(symbols, ignoreQualification); visitedSymbolTables.pop(); return result; } @@ -26005,20 +26608,20 @@ var ts; // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function isUMDExportSymbol(symbol) { return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } - function trySymbolTable(symbols) { + function trySymbolTable(symbols, ignoreQualification) { // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.escapedName))) { + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; } // Check if symbol is any of the alias @@ -26029,12 +26632,13 @@ var ts; // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; } // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + var candidateTable = getExportsOfSymbol(resolvedImportedSymbol); + var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -26089,6 +26693,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -26216,97 +26824,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 3112960 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 162 /* ConstructorType */ : 161 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 157 /* ConstructSignature */ : 156 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8 /* NoTruncation */) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256 /* UseFullyQualifiedType */) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096 /* SuppressAnyReturnType */) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1 /* WriteArrayAsGenericType */) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64 /* WriteTypeArgumentsOfSignature */) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; return undefined; @@ -26343,6 +26985,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); } if (type.flags & 2048 /* Void */) { @@ -26364,10 +27011,13 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -26381,7 +27031,7 @@ var ts; // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); return ts.createTypeReferenceNode(name, typeArgumentNodes); @@ -26394,7 +27044,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } return undefined; @@ -26420,7 +27070,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); @@ -26429,7 +27079,7 @@ var ts; var symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); @@ -26452,10 +27102,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + if (isConstructorObject) { + return createTypeNodeFromObjectType(type); + } + else { + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } } } else { @@ -26472,7 +27128,8 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -26497,11 +27154,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304 /* InObjectTypeLiteral */; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); @@ -26515,7 +27172,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -26529,12 +27186,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -26613,7 +27275,10 @@ var ts; typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); + var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? + createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration) : + resolvedType.stringIndexInfo; + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(indexInfo, 0 /* String */, context)); } if (resolvedType.numberIndexInfo) { typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); @@ -26624,9 +27289,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + } + } var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -26673,20 +27353,30 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); } var returnTypeNode; - if (signature.typePredicate) { - var typePredicate = signature.typePredicate; + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : ts.createThisTypeNode(); @@ -26697,7 +27387,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256 /* SuppressAnyReturnType */) { if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { returnTypeNode = undefined; } @@ -26705,14 +27395,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var savedContextFlags = context.flags; + context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -26723,7 +27416,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -26749,47 +27442,22 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -26817,11 +27485,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -26884,6 +27634,9 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -26893,7 +27646,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } switch (declaration.kind) { @@ -26912,882 +27665,161 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } + return links.isVisible; } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 177 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 227 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + // falls through + case 234 /* ModuleDeclaration */: + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 232 /* TypeAliasDeclaration */: + case 229 /* FunctionDeclaration */: + case 233 /* EnumDeclaration */: + case 238 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 238 /* ImportEqualsDeclaration */ && parent.kind !== 269 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { + return isGlobalSourceFile(parent); } - } - else if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || - // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 153 /* Constructor */: + case 157 /* ConstructSignature */: + case 156 /* CallSignature */: + case 158 /* IndexSignature */: + case 147 /* Parameter */: + case 235 /* ModuleBlock */: + case 161 /* FunctionType */: + case 162 /* ConstructorType */: + case 164 /* TypeLiteral */: + case 160 /* TypeReference */: + case 165 /* ArrayType */: + case 166 /* TupleType */: + case 167 /* UnionType */: + case 168 /* IntersectionType */: + case 169 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 240 /* ImportClause */: + case 241 /* NamespaceImport */: + case 243 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 146 /* TypeParameter */: + // Source file and namespace export are always visible + case 269 /* SourceFile */: + case 237 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 244 /* ExportAssignment */: + return false; + default: + return false; } } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 33585807 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - // In a literal enum type with a single member E { A }, E and E.A denote the - // same type. We always display this type simply as E. - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - } - else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024 /* UniqueESSymbol */) { - if (flags & 131072 /* AllowUniqueESSymbolType */) { - writeKeyword(writer, 140 /* UniqueKeyword */); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137 /* SymbolKeyword */); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288 /* Index */) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128 /* InElementType */); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - else if (type.flags & 1048576 /* IndexedAccess */) { - writeType(type.objectType, 128 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); + } + function collectLinkedAliases(node, setVisibility) { + var exportSymbol; + if (node.parent && node.parent.kind === 244 /* ExportAssignment */) { + exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + } + else if (node.parent.kind === 247 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (setVisibility) { + getNodeLinks(declaration).isVisible = true; } else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + result = result || []; + ts.pushIfUnique(result, resultNode); } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); } - writePunctuation(writer, 29 /* GreaterThanToken */); } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { - writeAnonymousType(type, flags); - } - else { - // Write the type reference in the format f.g.C where A and B are type arguments - // for outer type parameters, and f and g are the respective declaring containers of those - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - // When type parameters are their own type arguments for the whole group (i.e. we have - // the default outer type arguments), we don't show the group. - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 131072 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - // If type is an anonymous type literal in a type alias declaration, use type alias name - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - else { - // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead - // of types allows us to catch circular references to instantiations of the same anonymous type - // However, in case of class expressions, we want to write both the static side and the instance side. - // We skip adding the static side so that the instance side has a chance to be written - // before checking for circular references. - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || // is exported function symbol - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it - ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128 /* InElementType */) { - return true; - } - else if (flags & 512 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { - if (p.flags & 4194304 /* Prototype */) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 512 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 16 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } - function isDeclarationVisible(node) { - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } - return false; - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 177 /* BindingElement */: - return isDeclarationVisible(node.parent.parent); - case 227 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - // If the binding pattern is empty, this variable declaration is not visible - return false; - } - // falls through - case 234 /* ModuleDeclaration */: - case 230 /* ClassDeclaration */: - case 231 /* InterfaceDeclaration */: - case 232 /* TypeAliasDeclaration */: - case 229 /* FunctionDeclaration */: - case 233 /* EnumDeclaration */: - case 238 /* ImportEqualsDeclaration */: - // external module augmentation is always visible - if (ts.isExternalModuleAugmentation(node)) { - return true; - } - var parent = getDeclarationContainer(node); - // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 238 /* ImportEqualsDeclaration */ && parent.kind !== 269 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { - return isGlobalSourceFile(parent); - } - // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent); - case 150 /* PropertyDeclaration */: - case 149 /* PropertySignature */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - case 152 /* MethodDeclaration */: - case 151 /* MethodSignature */: - if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { - // Private/protected properties/methods are not visible - return false; - } - // Public properties/methods are visible if its parents are visible, so: - // falls through - case 153 /* Constructor */: - case 157 /* ConstructSignature */: - case 156 /* CallSignature */: - case 158 /* IndexSignature */: - case 147 /* Parameter */: - case 235 /* ModuleBlock */: - case 161 /* FunctionType */: - case 162 /* ConstructorType */: - case 164 /* TypeLiteral */: - case 160 /* TypeReference */: - case 165 /* ArrayType */: - case 166 /* TupleType */: - case 167 /* UnionType */: - case 168 /* IntersectionType */: - case 169 /* ParenthesizedType */: - return isDeclarationVisible(node.parent); - // Default binding, import specifier and namespace import is visible - // only on demand so by default it is not visible - case 240 /* ImportClause */: - case 241 /* NamespaceImport */: - case 243 /* ImportSpecifier */: - return false; - // Type parameters are always visible - case 146 /* TypeParameter */: - // Source file and namespace export are always visible - case 269 /* SourceFile */: - case 237 /* NamespaceExportDeclaration */: - return true; - // Export assignments do not create name bindings outside the module - case 244 /* ExportAssignment */: - return false; - default: - return false; - } - } - } - function collectLinkedAliases(node, setVisibility) { - var exportSymbol; - if (node.parent && node.parent.kind === 244 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); - } - else if (node.parent.kind === 247 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); - } - var result; - if (exportSymbol) { - buildVisibleNodeList(exportSymbol.declarations); - } - return result; - function buildVisibleNodeList(declarations) { - ts.forEach(declarations, function (declaration) { - var resultNode = getAnyImportSyntax(declaration) || declaration; - if (setVisibility) { - getNodeLinks(declaration).isVisible = true; - } - else { - result = result || []; - ts.pushIfUnique(result, resultNode); - } - if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { - // Add the referenced top container visible - var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); - if (importSymbol) { - buildVisibleNodeList(importSymbol.declarations); - } - } - }); - } - } - /** - * Push an entry on the type resolution stack. If an entry with the given target and the given property name - * is already on the stack, and no entries in between already have a type, then a circularity has occurred. - * In this case, the result values of the existing entry and all entries pushed after it are changed to false, - * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. - * In order to see if the same query has already been done before, the target object and the propertyName both - * must match the one passed in. - * - * @param target The symbol, type, or signature whose type is being queried - * @param propertyName The property name that should be used to query the target for its type - */ - function pushTypeResolution(target, propertyName) { - var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); - if (resolutionCycleStartIndex >= 0) { - // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { - resolutionResults[i] = false; - } - return false; - } - resolutionTargets.push(target); - resolutionResults.push(/*items*/ true); - resolutionPropertyNames.push(propertyName); - return true; - } - function findResolutionCycleStartIndex(target, propertyName) { - for (var i = resolutionTargets.length - 1; i >= 0; i--) { - if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { - return -1; - } - if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { - return i; + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; } } return -1; @@ -27805,6 +27837,10 @@ var ts; if (propertyName === 3 /* ResolvedReturnType */) { return target.resolvedReturnType; } + if (propertyName === 4 /* ResolvedBaseConstraint */) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will @@ -27929,7 +27965,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -27950,7 +27987,7 @@ var ts; } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -27971,7 +28008,7 @@ var ts; type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -27997,11 +28034,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === 216 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 216 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; } - if (declaration.parent.parent.kind === 217 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 217 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -28012,11 +28049,11 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } + var isOptional = !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken && includeOptionality; // Use type from type annotation if one is present - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - var declaredType = getTypeFromTypeNode(typeNode); - return addOptionality(declaredType, /*optional*/ !!declaration.questionToken && includeOptionality); + var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); + if (declaredType) { + return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && declaration.kind === 227 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && @@ -28058,23 +28095,19 @@ var ts; type = getContextuallyTypedParameterType(declaration); } if (type) { - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { var type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ !!declaration.questionToken && includeOptionality); + return addOptionality(type, isOptional); } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for return trueType; } - // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 266 /* ShorthandPropertyAssignment */) { - return checkIdentifier(declaration.name); - } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); @@ -28121,7 +28154,7 @@ var ts; types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); } } - var type = jsDocType || getUnionType(types, /*subtypeReduction*/ true); + var type = jsDocType || getUnionType(types, 2 /* Subtype */); return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if @@ -28215,19 +28248,13 @@ var ts; reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 1024 /* UniqueESSymbol */ && !declaration.type && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 1024 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } - // During a normal type check we'll never get to here with a property assignment (the check of the containing - // object literal uses a different path). We exclude widening only so that language services and type verification - // tools see the actual type. - if (declaration.kind === 265 /* PropertyAssignment */) { - return type; - } return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any - type = declaration.dotDotDotToken ? anyArrayType : anyType; + type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && noImplicitAny) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { @@ -28241,6 +28268,12 @@ var ts; var memberDeclaration = root.kind === 147 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } + function tryGetTypeFromEffectiveTypeNode(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { @@ -28274,9 +28307,39 @@ var ts; declaration.kind === 180 /* PropertyAccessExpression */ && declaration.parent.kind === 195 /* BinaryExpression */) { type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); } - else { + else if (ts.isJSDocPropertyTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } + else { + ts.Debug.fail("Unhandled declaration kind! " + ts.SyntaxKind[declaration.kind]); + } if (!popTypeResolution()) { type = reportCircularityError(symbol); } @@ -28443,6 +28506,9 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } + if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + return getTypeOfReverseMappedSymbol(symbol); + } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { return getTypeOfVariableOrParameterOrProperty(symbol); } @@ -28656,10 +28722,10 @@ var ts; return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = ts.emptyArray; + type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); @@ -28682,22 +28748,29 @@ var ts; var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; + return type.resolvedBaseTypes = ts.emptyArray; } baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === unknownType) { - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; + return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); - return; + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = ts.emptyArray; + } + if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { + // Circular reference, likely through instantiation of default parameters + // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset + // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a + // partial instantiation of the members without the base types fully resolved + type.members = undefined; } - type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [baseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -28735,7 +28808,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); } } else { @@ -28900,7 +28973,7 @@ var ts; } } if (memberTypeList.length) { - var enumType_1 = getUnionType(memberTypeList, /*subtypeReduction*/ false, symbol, /*aliasTypeArguments*/ undefined); + var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); if (enumType_1.flags & 131072 /* Union */) { enumType_1.flags |= 256 /* EnumLiteral */; enumType_1.symbol = symbol; @@ -28998,7 +29071,7 @@ var ts; */ function isThislessVariableLikeDeclaration(node) { var typeNode = ts.getEffectiveTypeAnnotationNode(node); - return typeNode ? isThislessType(typeNode) : !node.initializer; + return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node); } /** * A function-like declaration is considered free of `this` references if it has a return type @@ -29260,18 +29333,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -29301,6 +29375,7 @@ var ts; if (source.symbol && members === getMembersOfSymbol(source.symbol)) { members = ts.createSymbolTable(source.declaredProperties); } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); var thisArgument = ts.lastOrUndefined(typeArguments); for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { var baseType = baseTypes_1[_i]; @@ -29328,27 +29403,28 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; + sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasLiteralTypes = hasLiteralTypes; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -29359,7 +29435,7 @@ var ts; var baseSig = baseSignatures_1[_i]; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); - if (isJavaScript || (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount)) { + if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) { var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; @@ -29418,13 +29494,13 @@ var ts; var s = signature; // Union the result types when more than one signature matches if (unionSignatures.length > 1) { - s = cloneSignature(signature); + var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); + thisParameter = createSymbolWithType(signature.thisParameter, thisType); } - // Clear resolved return type we possibly got from cloneSignature - s.resolvedReturnType = undefined; + s = cloneSignature(signature); + s.thisParameter = thisParameter; s.unionSignatures = unionSignatures; } (result || (result = [])).push(s); @@ -29446,7 +29522,7 @@ var ts; indexTypes.push(indexInfo.type); isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union @@ -29542,6 +29618,7 @@ var ts; if (symbol.exports) { members = getExportsOfSymbol(symbol); } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); @@ -29573,6 +29650,23 @@ var ts; } } } + function resolveReverseMappedTypeMembers(type) { + var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); + var readonlyMask = type.mappedType.declaration.readonlyToken ? false : true; + var optionalMask = type.mappedType.declaration.questionToken ? 0 : 16777216 /* Optional */; + var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { + var prop = _a[_i]; + var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); + inferredProp.declarations = prop.declarations; + inferredProp.propertyType = getTypeOfSymbol(prop); + inferredProp.mappedType = type.mappedType; + members.set(prop.escapedName, inferredProp); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -29703,6 +29797,9 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } + else if (type.objectFlags & 2048 /* ReverseMapped */) { + resolveReverseMappedTypeMembers(type); + } else if (type.objectFlags & 16 /* Anonymous */) { resolveAnonymousTypeMembers(type); } @@ -29794,12 +29891,17 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { + // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. + // to avoid this, return `undefined`. + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -29823,29 +29925,30 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; @@ -29865,7 +29968,7 @@ var ts; return stringType; } if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -29881,7 +29984,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -29943,15 +30046,14 @@ var ts; } function createUnionOrIntersectionProperty(containingType, name) { var props; - var types = containingType.types; var isUnion = containingType.flags & 131072 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var current = types_5[_i]; + for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { + var current = _a[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); @@ -29982,8 +30084,8 @@ var ts; var propTypes = []; var declarations = []; var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; + for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { + var prop = props_1[_b]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -30096,7 +30198,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); + return getUnionType(propTypes, 2 /* Subtype */); } } return undefined; @@ -30154,7 +30256,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -30162,27 +30264,27 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; + var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 71 /* Identifier */) { - return { - kind: 1 /* Identifier */, - parameterName: parameterName ? parameterName.escapedText : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; + return createIdentifierTypePredicate(parameterName && parameterName.escapedText, // TODO: GH#18217 + parameterName && getTypePredicateParameterIndex(node.parent.parameters, parameterName), type); } else { - return { - kind: 0 /* This */, - type: getTypeFromTypeNode(node.type) - }; + return createThisTypePredicate(type); } } + function createIdentifierTypePredicate(parameterName, parameterIndex, type) { + return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; + } + function createThisTypePredicate(type) { + return { kind: 0 /* This */, type: type }; + } /** * Gets the minimum number of type arguments needed to satisfy all non-optional type * parameters. @@ -30289,11 +30391,8 @@ var ts; : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; } @@ -30303,7 +30402,7 @@ var ts; // b) It references `arguments` somewhere var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -30418,6 +30517,28 @@ var ts; return getTypeOfSymbol(signature.thisParameter); } } + function signatureHasTypePredicate(signature) { + return getTypePredicateOfSignature(signature) !== undefined; + } + function getTypePredicateOfSignature(signature) { + if (!signature.resolvedTypePredicate) { + if (signature.target) { + var targetTypePredicate = getTypePredicateOfSignature(signature.target); + signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; + } + else if (signature.unionSignatures) { + signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + } + else { + var declaration = signature.declaration; + signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 159 /* TypePredicate */ ? + createTypePredicateFromTypePredicateNode(declaration.type) : + noTypePredicate; + } + ts.Debug.assert(!!signature.resolvedTypePredicate); + } + return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -30428,7 +30549,7 @@ var ts; type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } else { type = getReturnTypeFromBody(signature.declaration); @@ -30575,12 +30696,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -30601,8 +30722,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type = types_6[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -30652,7 +30773,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) @@ -31093,14 +31214,14 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31165,7 +31286,8 @@ var ts; // expression constructs such as array literals and the || and ?: operators). Named types can // circularly reference themselves and therefore cannot be subtype reduced during their declaration. // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } if (types.length === 0) { return neverType; } @@ -31177,11 +31299,15 @@ var ts; if (typeSet.containsAny) { return anyType; } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsLiteralOrUniqueESSymbol) { - removeRedundantLiteralTypes(typeSet); + switch (unionReduction) { + case 1 /* Literal */: + if (typeSet.containsLiteralOrUniqueESSymbol) { + removeRedundantLiteralTypes(typeSet); + } + break; + case 2 /* Subtype */: + removeSubtypes(typeSet); + break; } if (typeSet.length === 0) { return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : @@ -31190,6 +31316,40 @@ var ts; } return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); } + function getUnionTypePredicate(signatures) { + var first; + var types = []; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; + var pred = getTypePredicateOfSignature(sig); + if (!pred) { + continue; + } + if (first) { + if (!typePredicateKindsMatch(first, pred)) { + // No common type predicate. + return undefined; + } + } + else { + first = pred; + } + types.push(pred.type); + } + if (!first) { + // No union signatures had a type predicate. + return undefined; + } + var unionType = getUnionType(types); + return ts.isIdentifierTypePredicate(first) + ? createIdentifierTypePredicate(first.parameterName, first.parameterIndex, unionType) + : createThisTypePredicate(unionType); + } + function typePredicateKindsMatch(a, b) { + return ts.isIdentifierTypePredicate(a) + ? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex + : !ts.isIdentifierTypePredicate(b); + } // This function assumes the constituent type list is sorted and deduplicated. function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { @@ -31219,7 +31379,7 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); } return links.resolvedType; } @@ -31252,8 +31412,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var type = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type)); } } @@ -31290,8 +31450,7 @@ var ts; // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), - /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); @@ -31320,7 +31479,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -31369,6 +31528,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -31442,42 +31602,64 @@ var ts; } return false; } + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // undefined if no transformation is possible. - function getTransformedIndexedAccessType(type) { + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); + if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a + // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen + // eventually anyway, but it easier to reason about. + if (ts.some(objectType.types, isMappedTypeToNever)) { + var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); + return getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { // If the index type is generic, or if the object type is generic and doesn't originate in an expression, // we are performing a higher-order index access where we cannot meaningfully access the properties of the @@ -31583,10 +31765,7 @@ var ts; if (right.flags & 131072 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, propagatedFlags); }); } - if (right.flags & 33554432 /* NonPrimitive */) { - return nonPrimitiveType; - } - if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */)) { + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */ | 33554432 /* NonPrimitive */)) { return left; } var members = ts.createSymbolTable(); @@ -31639,8 +31818,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= propagatedFlags; - spread.flags |= 2097152 /* FreshLiteral */ | 8388608 /* ContainsObjectLiteral */; + spread.flags |= propagatedFlags | 8388608 /* ContainsObjectLiteral */; spread.objectFlags |= (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } @@ -31860,7 +32038,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -31882,7 +32060,7 @@ var ts; result.target = typeParameter; return result; } - function cloneTypePredicate(predicate, mapper) { + function instantiateTypePredicate(predicate, mapper) { if (ts.isIdentifierTypePredicate(predicate)) { return { kind: 1 /* Identifier */, @@ -31900,7 +32078,6 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { // First create a fresh set of type parameters, then include a mapping from the old to the // new type parameters in the mapper function. Finally store this mapper in the new type @@ -31912,11 +32089,12 @@ var ts; tp.mapper = mapper; } } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } + // Don't compute resolvedReturnType and resolvedTypePredicate now, + // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) + // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), - /*resolvedReturnType*/ undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); result.target = signature; result.mapper = mapper; return result; @@ -32064,7 +32242,7 @@ var ts; } } if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { - return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return getUnionType(instantiateTypes(type.types, mapper), 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (type.flags & 262144 /* Intersection */) { return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); @@ -32269,7 +32447,7 @@ var ts; // with respect to T. var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); var related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : @@ -32289,11 +32467,13 @@ var ts; } var sourceReturnType = getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (targetTypePredicate) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate) { + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); } @@ -32408,7 +32588,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -32493,6 +32673,9 @@ var ts; } return false; } + function isIgnoredJsxProperty(source, sourceProp, targetMemberType) { + return source.flags & 67108864 /* JsxAttributes */ && !(isUnhyphenatedJsxName(sourceProp.escapedName) || targetMemberType); + } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. @@ -32520,10 +32703,24 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -32533,8 +32730,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } if (!message) { if (relation === comparableRelation) { @@ -33015,7 +33212,7 @@ var ts; } else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. + // A is the constraint of T. var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -33050,7 +33247,7 @@ var ts; } else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. + // A is the constraint of S. var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -33058,10 +33255,11 @@ var ts; return result; } } - else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. + else if (target.flags & 1048576 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -33195,6 +33393,9 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */)) { var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp && sourceProp !== targetProp) { + if (isIgnoredJsxProperty(source, sourceProp, getTypeOfSymbol(targetProp))) { + continue; + } var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { @@ -33405,6 +33606,9 @@ var ts; var result = -1 /* True */; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; + if (isIgnoredJsxProperty(source, prop, /*targetMemberType*/ undefined)) { + continue; + } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { @@ -33574,7 +33778,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -33765,17 +33969,25 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + result &= sourceTypePredicate !== undefined || targetTypePredicate !== undefined + ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) + // If they're both type predicates their return types will both be `boolean`, so no need to compare those. + : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } return result; } + function compareTypePredicatesIdentical(source, target, compareTypes) { + return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); + } function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -33801,7 +34013,7 @@ var ts; var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); return primaryTypes.length ? getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : - getUnionType(types, /*subtypeReduction*/ true); + getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. function getCommonSubtype(types) { @@ -33867,8 +34079,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -34059,7 +34271,7 @@ var ts; // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). - return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType)); + return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); @@ -34146,6 +34358,9 @@ var ts; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; + case 173 /* MappedType */: + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } @@ -34201,6 +34416,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -34211,6 +34427,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -34237,7 +34454,7 @@ var ts; function isTypeParameterAtTopLevel(type, typeParameter) { return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - /** Create an object with properties named in the string literal type. Every property has type `{}` */ + /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { @@ -34246,7 +34463,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4 /* Property */, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -34262,42 +34479,45 @@ var ts; * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source, target, mappedTypeStack) { + function inferTypeForHomomorphicMappedType(source, target) { + var key = source.id + "," + target.id; + if (reverseMappedCache.has(key)) { + return reverseMappedCache.get(key); + } + reverseMappedCache.set(key, undefined); + var type = createReverseMappedType(source, target); + reverseMappedCache.set(key, type); + return type; + } + function createReverseMappedType(source, target) { var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0 /* String */); - if (properties.length === 0 && !indexInfo) { + if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) { return undefined; } - var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var inference = createInferenceInfo(typeParameter); - var inferences = [inference]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 16777216 /* Optional */; - var members = ts.createSymbolTable(); + // If any property contains context sensitive functions that have been skipped, the source type + // is incomplete and we can't infer a meaningful input type. for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - var propType = getTypeOfSymbol(prop); - // If any property contains context sensitive functions that have been skipped, the source type - // is incomplete and we can't infer a meaningful input type. - if (propType.flags & 16777216 /* ContainsAnyFunctionType */) { + if (getTypeOfSymbol(prop).flags & 16777216 /* ContainsAnyFunctionType */) { return undefined; } - var checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; - var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); - inferredProp.declarations = prop.declarations; - inferredProp.type = inferTargetType(propType); - members.set(prop.escapedName, inferredProp); - } - if (indexInfo) { - indexInfo = createIndexInfo(inferTargetType(indexInfo.type), readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - inference.candidates = undefined; - inferTypes(inferences, sourceType, templateType, 0, mappedTypeStack); - return inference.candidates ? getUnionType(inference.candidates, /*subtypeReduction*/ true) : emptyObjectType; } + var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + reversed.source = source; + reversed.mappedType = target; + return reversed; + } + function getTypeOfReverseMappedSymbol(symbol) { + return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + } + function inferReverseMappedType(sourceType, target) { + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + var inference = createInferenceInfo(typeParameter); + inferTypes([inference], sourceType, templateType); + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -34312,10 +34532,11 @@ var ts; } return undefined; } - function inferTypes(inferences, originalSource, originalTarget, priority, mappedTypeStack) { + function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -34384,25 +34605,27 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - // We give lowest priority to inferences of implicitNeverType (which is used as the - // element type for empty array literals). Thus, inferences from empty array literals - // only matter when no other inferences are made. - var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } return; } } - else if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || ts.emptyArray; var targetTypes = target.typeArguments || ts.emptyArray; @@ -34418,15 +34641,15 @@ var ts; } } else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -34452,7 +34675,7 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2 /* NakedTypeVariable */; + priority |= 1 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -34496,9 +34719,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -34531,16 +34754,10 @@ var ts; // such that direct inferences to T get priority over inferences to Partial, for example. var inference = getInferenceInfoForType(constraintType.type); if (inference && !inference.isFixed) { - var key = (source.symbol ? getSymbolId(source.symbol) + "," : "") + getSymbolId(target.symbol); - if (ts.contains(mappedTypeStack, key)) { - return; - } - (mappedTypeStack || (mappedTypeStack = [])).push(key); - var inferredType = inferTypeForHomomorphicMappedType(source, target, mappedTypeStack); - mappedTypeStack.pop(); + var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4 /* MappedType */; + priority |= 2 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -34586,8 +34803,10 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromContravariantTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { + inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); @@ -34614,8 +34833,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -34647,7 +34866,7 @@ var ts; if (candidates.length > 1) { var objectLiterals = ts.filter(candidates, isObjectLiteralType); if (objectLiterals.length) { - var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true)); + var objectLiteralsType = getWidenedType(getUnionType(objectLiterals, 2 /* Subtype */)); return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectLiteralType(t); }), [objectLiteralsType]); } } @@ -34672,10 +34891,19 @@ var ts; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : - context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -34724,7 +34952,8 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -34919,8 +35148,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -34986,16 +35215,6 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576 /* 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) { @@ -35032,7 +35251,7 @@ var ts; parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -35071,7 +35290,7 @@ var ts; var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -35190,15 +35409,15 @@ var ts; // Apply a mapping function to a type and return the resulting type. If the source type // is a union type, the mapping function is applied to each constituent type and a union // of the resulting types is returned. - function mapType(type, mapper) { + function mapType(type, mapper, noReductions) { if (!(type.flags & 131072 /* Union */)) { return mapper(type); } var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35212,7 +35431,7 @@ var ts; } } } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; + return mappedTypes ? getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : mappedType; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -35263,7 +35482,7 @@ var ts; return elementType.flags & 16384 /* Never */ ? autoArrayType : createArrayType(elementType.flags & 131072 /* Union */ ? - getUnionType(elementType.types, /*subtypeReduction*/ true) : + getUnionType(elementType.types, 2 /* Subtype */) : elementType); } // We perform subtype reduction upon obtaining the final array type from an evolving array type. @@ -35278,8 +35497,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 16384 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -35325,10 +35544,7 @@ var ts; var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } + return apparentType !== unknownType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); } } return false; @@ -35578,7 +35794,7 @@ var ts; seenIncomplete = true; } } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete); } function getTypeAtFlowLoopLabel(flow) { // If we have previously computed the control flow type for the reference at @@ -35606,7 +35822,7 @@ var ts; // path that leads to the top. for (var i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -35626,7 +35842,7 @@ var ts; firstAntecedentType = flowType; } var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis + // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. var cached_1 = cache.get(key); @@ -35649,7 +35865,7 @@ var ts; } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } @@ -35680,6 +35896,23 @@ var ts; } return type; } + function isTypePresencePossible(type, propName, assumeTrue) { + if (getIndexInfoOfType(type, 0 /* String */)) { + return true; + } + var prop = getPropertyOfType(type, propName); + if (prop) { + return prop.flags & 16777216 /* Optional */ ? true : assumeTrue; + } + return !assumeTrue; + } + function narrowByInKeyword(type, literal, assumeTrue) { + if ((type.flags & (131072 /* Union */ | 65536 /* Object */)) || (type.flags & 32768 /* TypeParameter */ && type.isThisType)) { + var propName_1 = ts.escapeLeadingUnderscores(literal.text); + return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); + } + return type; + } function narrowTypeByBinaryExpression(type, expr, assumeTrue) { switch (expr.operatorToken.kind) { case 58 /* EqualsToken */: @@ -35691,10 +35924,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && (right_1.kind === 9 /* StringLiteral */ || right_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && (left_1.kind === 9 /* StringLiteral */ || left_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -35715,6 +35948,12 @@ var ts; break; case 93 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); + case 92 /* InKeyword */: + var target = getReferenceCandidate(expr.right); + if ((expr.left.kind === 9 /* StringLiteral */ || expr.left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isMatchingReference(reference, target)) { + return narrowByInKeyword(type, expr.left, assumeTrue); + } + break; case 26 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); } @@ -35799,7 +36038,7 @@ var ts; var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -35879,7 +36118,7 @@ var ts; return type; } var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; + var predicate = getTypePredicateOfSignature(signature); if (!predicate) { return type; } @@ -36013,22 +36252,28 @@ var ts; var parent = node.parent; return parent.kind === 180 /* PropertyAccessExpression */ || parent.kind === 182 /* CallExpression */ && parent.expression === node || - parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 204 /* NonNullExpression */ || + parent.kind === 177 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getDeclaredOrApparentType(symbol, node) { + function getApparentTypeForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - var type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } return type; } + function markAliasReferenced(symbol, location) { + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { @@ -36054,9 +36299,9 @@ var ts; return getTypeOfSymbol(symbol); } // We should only mark aliases as referenced if there isn't a local value declaration - // for the symbol. - if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); + // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that + if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) { + markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var declaration = localOrExportSymbol.valueDeclaration; @@ -36097,7 +36342,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -36133,6 +36378,7 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -36144,7 +36390,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || node.parent.kind === 204 /* NonNullExpression */ || @@ -36346,6 +36592,15 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. @@ -36380,11 +36635,6 @@ var ts; return type; } } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -36659,7 +36909,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -36680,7 +36930,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. indexOfParameter -= 1; @@ -36708,7 +36958,7 @@ var ts; // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; - if (node === declaration.initializer || node.kind === 58 /* EqualsToken */) { + if (ts.hasInitializer(declaration) && node === declaration.initializer) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); @@ -36797,7 +37047,7 @@ var ts; // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. @@ -36826,12 +37076,6 @@ var ts; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; - case 34 /* EqualsEqualsEqualsToken */: - case 32 /* EqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - // For completions after `x === ` - return node === operatorToken ? getTypeOfExpression(binaryExpression.left) : undefined; default: return undefined; } @@ -36860,10 +37104,10 @@ var ts; return mapType(type, function (t) { var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; - }); + }, /*noReductions*/ true); } function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { @@ -37032,12 +37276,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 198 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 183 /* NewExpression */: - if (node.kind === 94 /* NewKeyword */) { - return getContextualType(parent); - } - // falls through case 182 /* CallExpression */: + case 183 /* NewExpression */: return getContextualTypeForArgument(parent, node); case 185 /* TypeAssertionExpression */: case 203 /* AsExpression */: @@ -37072,12 +37312,6 @@ var ts; case 252 /* JsxOpeningElement */: case 251 /* JsxSelfClosingElement */: return getAttributesTypeFromJsxOpeningLikeElement(parent); - case 261 /* CaseClause */: { - if (node.kind === 73 /* CaseKeyword */) { - var switchStatement = parent.parent.parent; - return getTypeOfExpression(switchStatement.expression); - } - } } return undefined; } @@ -37088,7 +37322,7 @@ var ts; // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + var signatures = getSignaturesOfType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -37141,8 +37375,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -37163,8 +37397,6 @@ var ts; var result; if (signatureList) { result = cloneSignature(signatureList[0]); - // Clear resolved return type we possibly got from cloneSignature - result.resolvedReturnType = undefined; result.unionSignatures = signatureList; } return result; @@ -37238,7 +37470,7 @@ var ts; if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -37248,7 +37480,7 @@ var ts; } } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : + getUnionType(elementTypes, 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { @@ -37320,7 +37552,7 @@ var ts; propTypes.push(getTypeOfSymbol(properties[i])); } } - var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; return createIndexInfo(unionType, /*isReadonly*/ false); } function checkObjectLiteral(node, checkMode) { @@ -37330,7 +37562,7 @@ var ts; var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 0; + var propagatedFlags = 2097152 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 175 /* ObjectBindingPattern */ || contextualType.pattern.kind === 179 /* ObjectLiteralExpression */); @@ -37499,13 +37731,13 @@ var ts; type.flags & 65536 /* Object */ && !isGenericMappedType(type) || type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node); + function checkJsxSelfClosingElement(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); return getJsxGlobalElementType() || anyType; } - function checkJsxElement(node) { + function checkJsxElement(node, checkMode) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -37515,8 +37747,8 @@ var ts; } return getJsxGlobalElementType() || anyType; } - function checkJsxFragment(node) { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); + function checkJsxFragment(node, checkMode) { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); if (compilerOptions.jsx === 2 /* React */ && compilerOptions.jsxFactory) { error(node, ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory); } @@ -37544,6 +37776,11 @@ var ts; ts.Debug.fail(); } } + function checkJsxAttribute(node, checkMode) { + return node.initializer + ? checkExpressionForMutableLocation(node.initializer, checkMode) + : trueType; // is sugar for + } /** * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. * @@ -37553,11 +37790,10 @@ var ts; * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, * which also calls getSpreadType. */ - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; var attributesTable = ts.createSymbolTable(); var spread = emptyObjectType; - var attributesArray = []; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; @@ -37566,9 +37802,7 @@ var ts; var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; // is sugar for + var exprType = checkJsxAttribute(attributeDecl, checkMode); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -37578,24 +37812,22 @@ var ts; attributeSymbol.type = exprType; attributeSymbol.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); - attributesArray.push(attributeSymbol); if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } } else { ts.Debug.assert(attributeDecl.kind === 259 /* JsxSpreadAttribute */); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - attributesArray = []; + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpression(attributeDecl.expression); + var exprType = checkExpressionCached(attributeDecl.expression, checkMode); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*propagatedFlags*/ 0); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 67108864 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -37603,18 +37835,8 @@ var ts; } } if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable), openingLikeElement.symbol, /*propagatedFlags*/ 0); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createSymbolTable(); - for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { - var attr = attributesArray_1[_b]; - if (!filter || filter(attr)) { - attributesTable.set(attr.escapedName, attr); - } + if (attributesTable.size > 0) { + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 67108864 /* JsxAttributes */); } } // Handle children attribute @@ -37629,27 +37851,27 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process + // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + createArrayType(getUnionType(childrenTypes)); + var childPropMap = ts.createSymbolTable(); + childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, 67108864 /* JsxAttributes */); } } if (hasSpreadAnyType) { return anyType; } - var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); - return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : - typeToIntersect ? typeToIntersect : attributeType; + return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable * @param attributesTable a symbol table of attributes property */ - function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + function createJsxAttributesType() { + var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); result.flags |= 67108864 /* JsxAttributes */ | 8388608 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; @@ -37678,7 +37900,7 @@ var ts; * @param node a JSXAttributes to be resolved of its type */ function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); + return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode); } function getJsxType(name) { var jsxType = jsxTypes.get(name); @@ -37730,7 +37952,7 @@ var ts; * element is not a class element, or the class element type cannot be determined, returns 'undefined'. * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ - function getJsxElementInstanceType(node, valueType) { + function getJsxElementInstanceType(node, valueType, sourceAttributesType) { ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' @@ -37747,19 +37969,27 @@ var ts; return unknownType; } } - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0, isJavascript); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); + if (sourceAttributesType) { + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); + var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); + } } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + } + else { + // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing + return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37927,19 +38157,19 @@ var ts; * * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature + * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) * @return attributes type if able to resolve the type of node * anyType if there is no type ElementAttributesProperty or there is an error * emptyObjectType if there is no "prop" in the element instance type */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType === void 0) { elementType = checkExpression(openingLikeElement.tagName); } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), /*subtypeReduction*/ true); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + }), 2 /* Subtype */); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type if (elementType.flags & 2 /* String */) { @@ -37967,7 +38197,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -37977,7 +38207,7 @@ var ts; return statelessAttributesType; } // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { + if (elementClassType && sourceAttributesType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } if (isTypeAny(elemInstanceType)) { @@ -38053,14 +38283,20 @@ var ts; * @param node a custom JSX opening-like element * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { + if (!sourceAttributesType) { + // This ensures we cache non-inference uses of this calculation (ie, contextual types or services) + var links = getNodeLinks(node); + var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; + if (!links[linkLocation]) { + var elemClassType = getJsxGlobalElementClassType(); + return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); + } + return links[linkLocation]; + } + else { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } - return links[linkLocation]; } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -38074,7 +38310,7 @@ var ts; else { // Because in language service, the given JSX opening-like element may be incomplete and therefore, // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ true); } } /** @@ -38087,7 +38323,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); + return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ false); } } /** @@ -38139,7 +38375,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node) { + function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -38161,7 +38397,7 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node); + checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); } else { checkJsxChildren(node.parent); @@ -38207,22 +38443,20 @@ var ts; * Check assignablity between given attributes property, "source attributes", and the "target attributes" * @param openingLikeElement an opening-like JSX element to check its JSXAttributes */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { // The function involves following steps: // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); - }); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); + // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, /*shouldIncludeAllStatelessAttributesType*/ false); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { @@ -38232,12 +38466,17 @@ var ts; // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { var attribute = _a[_i]; - if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attribute.name), typeToString(targetAttributesType)); + if (!ts.isJsxAttribute(attribute)) { + continue; + } + var attrName = attribute.name; + var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); // We break here so that errors won't be cascading break; } @@ -38367,16 +38606,16 @@ var ts; return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } @@ -38390,15 +38629,20 @@ var ts; } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { var propType; - var leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - var leftWasReferenced = leftSymbol && getSymbolLinks(leftSymbol).referenced; var leftType = checkNonNullExpression(left); + var parentSymbol = getNodeLinks(left).resolvedSymbol; var apparentType = getApparentType(getWidenedType(leftType)); if (isTypeAny(apparentType) || apparentType === silentNeverType) { + if (ts.isIdentifier(left) && parentSymbol) { + markAliasReferenced(parentSymbol, node); + } return apparentType; } var assignmentKind = ts.getAssignmentTargetKind(node); var prop = getPropertyOfType(apparentType, right.escapedText); + if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + markAliasReferenced(parentSymbol, node); + } if (!prop) { var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { @@ -38415,12 +38659,6 @@ var ts; else { checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, left.kind === 99 /* ThisKeyword */); - // Reset the referenced-ness of the LHS expression if this access refers to a const enum or const enum only module - leftSymbol = getNodeLinks(left) && getNodeLinks(left).resolvedSymbol; - if (leftSymbol && !leftWasReferenced && getSymbolLinks(leftSymbol).referenced && - !(isNonLocalAlias(leftSymbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(prop))) { - getSymbolLinks(leftSymbol).referenced = undefined; - } getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); if (assignmentKind) { @@ -38429,7 +38667,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -38496,6 +38734,9 @@ var ts; * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. */ function isPropertyDeclaredInAncestorClass(prop) { + if (!(prop.parent.flags & 32 /* Class */)) { + return false; + } var classType = getTypeOfSymbol(prop.parent); while (true) { classType = getSuperClass(classType); @@ -38542,7 +38783,7 @@ var ts; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -38647,32 +38888,43 @@ var ts; return res > max ? undefined : res; } 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; - } - else { - prop.isReferenced = true; + if (!prop || !noUnusedIdentifiers || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + return; + } + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + return; + } + 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; + } + else { + prop.isReferenced = true; + } } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 180 /* PropertyAccessExpression */ - ? node.expression - : node.left; + var left = node.kind === 180 /* PropertyAccessExpression */ ? node.expression : node.left; return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); } + function isValidPropertyAccessForCompletions(node, type, property) { + return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); + } + function isValidMethodAccess(method, type) { + var propType = getTypeOfFuncClassEnumModule(method); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); + ts.Debug.assert(signatures.length !== 0); + return signatures.some(function (sig) { + var thisType = getThisTypeOfSignature(sig); + return !thisType || isTypeAssignableTo(type, thisType); + }); + } function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(type, propertyName); @@ -38977,10 +39229,15 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } + function inferJsxTypeArguments(signature, sourceAttributesType, context) { + var paramType = getTypeAtPosition(signature, 0); + inferTypes(context.inferences, sourceAttributesType, paramType); + return getInferredTypes(context); + } function inferTypeArguments(node, signature, args, excludeArgument, context) { // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { @@ -39017,7 +39274,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -39073,7 +39330,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -39682,7 +39939,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { excludeArgument = undefined; @@ -39721,7 +39978,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -39755,7 +40012,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); } return resolveErrorCall(node); } @@ -39836,7 +40093,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -39876,6 +40133,26 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 /* Call */ + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -39889,7 +40166,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -39937,6 +40214,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -39981,8 +40259,8 @@ var ts; if (elementType.flags & 131072 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -40166,16 +40444,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default" /* Default */)) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); newSymbol.target = resolveSymbol(symbol); @@ -40183,7 +40463,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -40265,7 +40545,7 @@ var ts; var type = getTypeOfSymbol(symbol); if (strictNullChecks) { var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { + if (declaration && ts.hasInitializer(declaration)) { return getOptionalType(type); } } @@ -40374,7 +40654,6 @@ var ts; return promiseType; } function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } @@ -40391,9 +40670,9 @@ var ts; } } else { - var types = void 0; + var types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (functionFlags & 1 /* Generator */) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), types); if (!types || types.length === 0) { var iterableIteratorAny = functionFlags & 2 /* Async */ ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function @@ -40405,7 +40684,6 @@ var ts; } } else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); if (!types) { // For an async function, the return type will not be never, but rather a Promise for never. return functionFlags & 2 /* Async */ @@ -40420,8 +40698,9 @@ var ts; } } // Return a union of the return expression types. - type = getUnionType(types, /*subtypeReduction*/ true); + type = getUnionType(types, 2 /* Subtype */); } + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!contextualSignature) { reportErrorsFromWidening(func, type); } @@ -40503,6 +40782,7 @@ var ts; } return true; } + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -40528,8 +40808,7 @@ var ts; hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 187 /* FunctionExpression */ || func.kind === 188 /* ArrowFunction */)) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { @@ -40537,6 +40816,17 @@ var ts; } return aggregatedTypes; } + function mayReturnNever(func) { + switch (func.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + return true; + case 152 /* MethodDeclaration */: + return func.parent.kind === 179 /* ObjectLiteralExpression */; + default: + return false; + } + } /** * TypeScript Specification 1.0 (6.3) - July 2014 * An explicitly typed function whose return type isn't the Void type, @@ -40838,8 +41128,8 @@ var ts; } if (type.flags & 393216 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40914,6 +41204,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -41254,7 +41547,7 @@ var ts; leftType; case 54 /* BarBarToken */: return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) : + getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: checkAssignmentOperator(rightType); @@ -41390,7 +41683,7 @@ var ts; checkExpression(node.condition); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); - return getUnionType([type1, type2], /*subtypeReduction*/ true); + return getUnionType([type1, type2], 2 /* Subtype */); } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -41409,7 +41702,7 @@ var ts; node.contextualType = contextualType; node.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : - contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; + contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; var result = checkExpression(node, checkMode); node.contextualType = saveContextualType; node.contextualMapper = saveContextualMapper; @@ -41418,6 +41711,9 @@ var ts; function checkExpressionCached(node, checkMode) { var links = getNodeLinks(node); if (!links.resolvedType) { + if (checkMode) { + return checkExpression(node, checkMode); + } // When computing a type that we're going to cache, we need to ignore any ongoing control flow // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart // to the top of the stack ensures all transient types are computed from a known point. @@ -41440,12 +41736,12 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 131072 /* Union */ && !(contextualType.flags & 8 /* Boolean */)) { + if (contextualType.flags & 393216 /* UnionOrIntersection */ && !(contextualType.flags & 8 /* Boolean */)) { // If the contextual type is a union containing both of the 'true' and 'false' types we // don't consider it a literal context for boolean literals. - var types_19 = contextualType.types; - return ts.some(types_19, function (t) { - return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_19, trueType) && containsType(types_19, falseType)) && + var types_18 = contextualType.types; + return ts.some(types_18, function (t) { + return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_18, trueType) && containsType(types_18, falseType)) && isLiteralOfContextualType(candidateType, t); }); } @@ -41571,9 +41867,10 @@ var ts; // - target in rhs of import statement var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -41665,11 +41962,11 @@ var ts; case 260 /* JsxExpression */: return checkJsxExpression(node, checkMode); case 250 /* JsxElement */: - return checkJsxElement(node); + return checkJsxElement(node, checkMode); case 251 /* JsxSelfClosingElement */: - return checkJsxSelfClosingElement(node); + return checkJsxSelfClosingElement(node, checkMode); case 254 /* JsxFragment */: - return checkJsxFragment(node); + return checkJsxFragment(node, checkMode); case 258 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); case 252 /* JsxOpeningElement */: @@ -41718,7 +42015,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { @@ -41749,7 +42046,7 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); if (!typePredicate) { return; } @@ -41764,7 +42061,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } @@ -42095,22 +42392,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && @@ -42326,6 +42607,9 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); + if (noImplicitAny && !node.type) { + reportImplicitAnyError(node, anyType); + } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); @@ -42693,7 +42977,7 @@ var ts; } return undefined; } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); } /** * Gets the "awaited type" of a type. @@ -42726,7 +43010,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -42926,7 +43210,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -43283,22 +43567,35 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 152 /* MethodDeclaration */ || member.kind === 150 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. + break; } - } - else if (member.kind === 153 /* Constructor */) { + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } } - } + break; + case 158 /* IndexSignature */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } @@ -43615,7 +43912,9 @@ var ts; // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); - checkSourceElement(node.type); + if (!ts.isBindingElement(node)) { + checkSourceElement(node.type); + } // JSDoc `function(string, string): string` syntax results in parameters with no name if (!node.name) { return; @@ -43664,13 +43963,19 @@ var ts; if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + } checkParameterInitializer(node); } return; } var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + var type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -43865,7 +44170,7 @@ var ts; // Grammar checking checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 + // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, @@ -43954,7 +44259,7 @@ var ts; var arrayTypes = inputType.types; var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } else if (arrayType.flags & 524322 /* StringLike */) { @@ -43999,7 +44304,7 @@ var ts; if (arrayElementType.flags & 524322 /* StringLike */) { return stringType; } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + return getUnionType([arrayElementType, stringType], 2 /* Subtype */); } return arrayElementType; } @@ -44086,7 +44391,7 @@ var ts; } return undefined; } - var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); if (checkAssignability && errorNode && iteratedType) { // If `checkAssignability` was specified, we were called from @@ -44154,7 +44459,7 @@ var ts; } return undefined; } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), 2 /* Subtype */); if (isTypeAny(nextResult)) { return undefined; } @@ -44209,56 +44514,56 @@ var ts; } function checkReturnStatement(node) { // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } + if (checkGrammarStatementInAmbientContext(node)) { + return; } var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { + if (!func) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + return; + } + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var functionFlags = ts.getFunctionFlags(func); + var isGenerator = functionFlags & 1 /* Generator */; + if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + if (isGenerator) { // A generator does not need its return expressions checked against its return type. // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added + // TODO: Check return types of generators when return type tracking is added // for generators. return; } - if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 155 /* SetAccessor */) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } + else if (func.kind === 155 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 153 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } + } + else if (func.kind === 153 /* Constructor */) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - // If the function has a return type, but promisedType is - // undefined, an error will be reported in checkAsyncFunctionReturnType - // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2 /* Async */) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); } } + else { + checkTypeAssignableTo(exprType, returnType, node); + } } - else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - // The function has a return type, but the return statement doesn't have an expression. - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } + } + else if (func.kind !== 153 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkWithStatement(node) { @@ -44420,7 +44725,8 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -44539,9 +44845,11 @@ var ts; // type parameter at this position, we report an error. var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; + if (sourceConstraint) { + // relax check if later interface augmentation has no constraint + if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { + return false; + } } // If the type parameter node has a default and it is not identical to the default // for the type parameter at this position, we report an error. @@ -44614,7 +44922,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -44644,7 +44955,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -44659,6 +44976,35 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(baseWithThis)); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { @@ -44962,6 +45308,7 @@ var ts; case 37 /* PlusToken */: return left + right; case 38 /* MinusToken */: return left - right; case 42 /* PercentToken */: return left % right; + case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } break; @@ -46186,6 +46533,7 @@ var ts; } return undefined; case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript @@ -46311,7 +46659,7 @@ var ts; // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -46358,35 +46706,28 @@ var ts; return ts.typeHasCallOrConstructSignatures(type, checker); } function getRootSymbols(symbol) { + var roots = getImmediateRootSymbols(symbol); + return roots ? ts.flatMap(roots, getRootSymbols) : [symbol]; + } + function getImmediateRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { - var symbols_4 = []; - var name_4 = symbol.escapedName; - ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_4); - if (symbol) { - symbols_4.push(symbol); - } - }); - return symbols_4; + return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); }); } else if (symbol.flags & 33554432 /* Transient */) { - var transient = symbol; - if (transient.leftSpread) { - return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); - } - if (transient.syntheticOrigin) { - return getRootSymbols(transient.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } + var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin; + return leftSpread ? [leftSpread, rightSpread] + : syntheticOrigin ? [syntheticOrigin] + : ts.singleElementArray(tryGetAliasTarget(symbol)); + } + return undefined; + } + function tryGetAliasTarget(symbol) { + var target; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; } - return [symbol]; + return target; } // Emitter support function isArgumentsLocalBinding(node) { @@ -46494,7 +46835,7 @@ var ts; // AND // - binding is not declared in loop, should be renamed to avoid name reuse across siblings // let a, b - // { let x = 1; a = () => x; } + // { let x = 1; a = () => x; } // { let x = 100; b = () => x; } // console.log(a()); // should print '1' // console.log(b()); // should print '100' @@ -46737,20 +47078,20 @@ var ts; : unknownType; if (type.flags & 1024 /* UniqueESSymbol */ && type.symbol === symbol) { - flags |= 131072 /* AllowUniqueESSymbolType */; + flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 8192 /* AddUndefined */) { + if (flags & 131072 /* AddUndefined */) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -47350,9 +47691,6 @@ var ts; } } function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } if (typeParameters && typeParameters.length === 0) { var start = typeParameters.pos - "<".length; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; @@ -47436,6 +47774,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -47896,12 +48241,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); @@ -48095,7 +48443,7 @@ var ts; if (node.flags & 2097152 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } - if (node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || + if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } @@ -48360,7 +48708,7 @@ var ts; var node = createSynthesizedNode(71 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; - node.autoGenerateKind = 0 /* None */; + node.autoGenerateFlags = 0 /* None */; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -48375,22 +48723,24 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - /** Create a unique temporary variable. */ - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateFlags = 1 /* Auto */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + } return name; } ts.createTempVariable = createTempVariable; /** Create a unique temporary variable for use in a loop. */ function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateFlags = 2 /* Loop */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -48399,7 +48749,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateFlags = 3 /* Unique */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -48407,10 +48757,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4 /* Node */; + name.autoGenerateFlags = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; + } nextAutoGenerateId++; return name; } @@ -48708,11 +49060,12 @@ var ts; } ts.updateIndexSignature = updateIndexSignature; /* @internal */ - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -51575,13 +51928,13 @@ var ts; if (isLeftSideOfBinary) { // No need to parenthesize the left operand when the binary operator is // left associative: - // (a*b)/x -> a*b/x - // (a**b)/x -> a**b/x + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x // // Parentheses are needed for the left operand when the binary operator is // right associative: - // (a/b)**x -> (a/b)**x - // (a**b)**x -> (a**b)**x + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x return binaryOperatorAssociativity === 1 /* Right */; } else { @@ -51681,7 +52034,9 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || + emittedExpression.kind === 293 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -52331,6 +52686,7 @@ var ts; /// var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -52465,7 +52821,7 @@ var ts; switch (kind) { // Names case 71 /* Identifier */: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145 /* ComputedPropertyName */: @@ -52612,7 +52968,7 @@ var ts; case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217 /* ForOfStatement */: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219 /* BreakStatement */: @@ -53436,6 +53792,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -53535,7 +53892,12 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { // If the right-hand value of the destructuring assignment needs to be preserved (as // is the case when the destructuring assignment is part of a larger expression), // then we need to cache the right-hand value. @@ -53579,6 +53941,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -53606,6 +53988,15 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -53994,7 +54385,7 @@ var ts; */ var classAliases; /** - * Keeps track of whether we are within any containing namespaces when performing + * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; @@ -54691,11 +55082,14 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. @@ -56864,7 +57258,7 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -56878,6 +57272,7 @@ var ts; * just-in-time substitution for `super` expressions inside of async methods. */ var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -56915,6 +57310,83 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 215 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 216 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 217 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 264 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 208 /* Block */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 221 /* WithStatement */: + case 223 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } /** * Visits an AwaitExpression node. * @@ -56989,6 +57461,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -57001,10 +57540,17 @@ var ts; // `this` and `arguments` objects to `__awaiter`. The generator function // passed to `__awaiter` is executed inside of the callback to the // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -57020,27 +57566,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -57304,7 +57851,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); @@ -57316,8 +57863,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -57818,7 +58365,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncIterator) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -59001,7 +59548,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -60185,7 +60732,7 @@ var ts; ])); } /** - * Visits an ObjectLiteralExpression with computed propety names. + * Visits an ObjectLiteralExpression with computed property names. * * @param node An ObjectLiteralExpression node. */ @@ -64101,8 +64648,8 @@ var ts; // `throw` methods that step through the generator when invoked. // // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. // // variables: // _ Persistent state for the generator that is shared between the helper and the @@ -64282,7 +64829,7 @@ var ts; // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: @@ -64307,6 +64854,8 @@ var ts; ]))) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Transforms a SourceFile into a UMD module. @@ -64357,7 +64906,7 @@ var ts; // define(["require", "exports"], factory); // } // })(function ...) - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: @@ -64375,6 +64924,8 @@ var ts; ])) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Collect the additional asynchronous dependencies for the module. @@ -64426,6 +64977,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } /** * Transforms a SourceFile into an AMD or UMD module body. * @@ -64440,6 +65002,9 @@ var ts; } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); // Append the 'export =' statement if provided. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); @@ -64611,7 +65176,12 @@ var ts; ts.setEmitFlags(func, 8 /* CapturesThis */); } } - return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") @@ -64621,6 +65191,10 @@ var ts; // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } var func; if (languageVersion >= 2 /* ES2015 */) { func = ts.createArrowFunction( @@ -64647,6 +65221,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } /** * Visits an ImportDeclaration node. * @@ -64665,7 +65253,7 @@ var ts; if (namespaceDeclaration && !ts.isDefaultImport(node)) { // import * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { // import d from "mod"; @@ -64673,7 +65261,7 @@ var ts; // import d, { x, y } from "mod"; // import d, * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node))); @@ -65406,6 +65994,18 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); /// /// @@ -65423,6 +66023,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. @@ -66656,6 +67257,43 @@ var ts; if (hint === 1 /* Expression */) { return substituteExpression(node); } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 266 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } return node; } /** @@ -66846,9 +67484,11 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration( + var tslibImport = ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67522,9 +68162,9 @@ var ts; * @param tokenStartPos The start pos of the token. * @param emitCallback The callback used to emit the token. */ - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -67533,7 +68173,7 @@ var ts; if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { @@ -67558,7 +68198,7 @@ var ts; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -68099,8 +68739,8 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { - // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { + // if file was external module this fact should be preserved in .d.ts as well. // in case if we didn't write any external module specifiers in .d.ts we need to emit something // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); @@ -68278,9 +68918,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 /* UseTypeOfFunction */ | - 16384 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -68294,7 +68934,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); errorNameNode = undefined; } } @@ -68532,12 +69172,15 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); write(";"); writeLine(); return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators + } if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -68625,6 +69268,7 @@ var ts; var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators write("export "); } if (modifiers & 512 /* Default */) { @@ -68766,6 +69410,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -69199,7 +69844,7 @@ var ts; // if this is property of type literal, // or is parameter of method/call/construct/index signature of type literal // emit only if type is specified - if (node.type) { + if (ts.hasType(node)) { write(": "); emitType(node.type); } @@ -69650,6 +70295,7 @@ var ts; // it allows emitSeparatedList to write separator appropriately) // Example: // original: function foo([, x, ,]) {} + // tslint:disable-next-line no-double-space // emit : function foo([ , x, , ]) {} write(" "); } @@ -69767,7 +70413,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -69798,7 +70444,6 @@ var ts; /// var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ /** @@ -69818,7 +70463,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -69827,7 +70475,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -69960,7 +70611,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -70026,16 +70677,29 @@ var ts; var generatedNames; // Set of names generated by the NameGenerator. var tempFlagsStack; // Stack of enclosing name generation scopes. var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { // public API printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, // internal API writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -70058,6 +70722,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -70073,6 +70741,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -70100,7 +70778,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -70126,6 +70804,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0 /* Auto */; + reservedNamesStack = []; comments.reset(); setWriter(/*output*/ undefined); } @@ -70189,7 +70868,9 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { @@ -70198,7 +70879,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -70436,7 +71117,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -70460,7 +71141,7 @@ var ts; case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: case 91 /* ImportKeyword */: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; // Expressions case 178 /* ArrayLiteralExpression */: @@ -70556,25 +71237,27 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); } } // // Identifiers // function emitIdentifier(node) { - write(getTextOfNode(node, /*includeTrivia*/ false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names // function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -70586,36 +71269,46 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } // // Signature elements // function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } // @@ -70624,19 +71317,19 @@ var ts; function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -70645,8 +71338,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -70658,13 +71351,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); + writeKeyword(node.kind === 154 /* GetAccessor */ ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -70673,34 +71367,37 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } // // Types // function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -70710,7 +71407,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -70732,34 +71431,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); @@ -70768,29 +71472,29 @@ var ts; emitList(node, node.types, 264 /* IntersectionTypeConstituents */); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -70798,23 +71502,24 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); @@ -70823,32 +71528,24 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("{}"); - } - else { - write("{"); - emitList(node, elements, 432 /* ObjectBindingPatternElements */); - write("}"); - } + writePunctuation("{"); + emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - write("["); - emitList(node, node.elements, 304 /* ArrayBindingPatternElements */); - write("]"); - } + writePunctuation("["); + emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Expressions @@ -70885,7 +71582,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -70911,9 +71608,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -70921,26 +71618,27 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -70953,30 +71651,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -71000,7 +71702,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; @@ -71009,7 +71711,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -71037,12 +71739,12 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -71055,17 +71757,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } // @@ -71079,13 +71783,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; @@ -71094,27 +71798,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, node); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, node); + var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, node); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); + writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212 /* IfStatement */) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -71123,55 +71827,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -71185,58 +71897,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, /*contextNode*/ contextNode); + pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -71244,24 +71960,26 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos); - write(";"); + writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); + writeSemicolon(); } // // Declarations // function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { @@ -71270,9 +71988,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -71302,19 +72020,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: @@ -71347,7 +72065,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -71359,7 +72078,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, body); + writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -71384,17 +72103,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -71402,66 +72125,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* HeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* InterfaceMembers */); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81 /* EnumMembers */); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512 /* GlobalAugmentation */) { - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234 /* ModuleDeclaration */) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end); + writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71 /* Identifier */) { @@ -71473,23 +72207,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -71499,28 +72240,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -71529,14 +72286,16 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } @@ -71544,9 +72303,10 @@ var ts; // Module references // function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } // // JSX @@ -71557,14 +72317,14 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -71572,45 +72332,46 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -71625,13 +72386,15 @@ var ts; // Clauses // function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -71658,25 +72421,25 @@ var ts; } var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); - write(" "); + var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } @@ -71685,7 +72448,8 @@ var ts; // function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); // This is to ensure that we emit comment in the following case: // For example: // obj = { @@ -71703,13 +72467,15 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } @@ -71718,7 +72484,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Top-level nodes @@ -71816,33 +72582,60 @@ var ts; // // Helpers // + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328 /* Modifiers */); - write(" "); + writeSpace(); + } + } + function emitTypeAnnotation(node) { + if (node) { + writePunctuation(":"); + writeSpace(); + emit(node); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } } - function emitNodeWithPrefix(prefix, node, emit) { + function emitWithLeadingSpace(node) { if (node) { - write(prefix); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { - write(" "); + writeSpace(); emit(node); } else { @@ -71856,13 +72649,16 @@ var ts; emitList(parentNode, decorators, 24577 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360 /* Parameters */); + emitList(parentNode, parameters, 1296 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -71882,7 +72678,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -71897,6 +72693,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -71915,7 +72728,7 @@ var ts; return; } if (format & 7680 /* BracketsMask */) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -71926,7 +72739,7 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { - write(" "); + writeSpace(); } } else { @@ -71938,7 +72751,7 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } // Increase the indent, if requested. if (format & 64 /* Indented */) { @@ -71947,7 +72760,6 @@ var ts; // Emit each child. var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -71958,10 +72770,10 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new @@ -71974,7 +72786,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { - write(" "); + writeSpace(); } } // Emit this child. @@ -71997,7 +72809,7 @@ var ts; // Write a trailing comma, if requested. var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { - write(","); + writePunctuation(","); } // Emit any trailing comment of the last element in the list // i.e @@ -72005,7 +72817,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -72017,50 +72829,102 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -72251,6 +73115,7 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } /** * Pop the current name generation scope. @@ -72260,15 +73125,22 @@ var ts; return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } /** * Generate the text for a generated identifier. */ function generateName(name) { - if (name.autoGenerateKind === 4 /* Node */) { + if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.skipNameGenerationScope) { + if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { var savedTempFlags = tempFlags; popNameGenerationScope(/*node*/ undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -72298,7 +73170,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } /** * Returns a value indicating whether a name is unique within a container. @@ -72320,11 +73193,14 @@ var ts; * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. */ - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 /* _i */ ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -72337,6 +73213,9 @@ var ts; ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -72429,11 +73308,11 @@ var ts; * Generates a unique identifier for a node. */ function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); } @@ -72451,7 +73330,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateFlags === 4 /* Node */ && node.autoGenerateId !== autoGenerateId) { break; } @@ -72462,17 +73341,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0 /* None */] = ""; - delimiters[16 /* CommaDelimited */] = ","; - delimiters[4 /* BarDelimited */] = " |"; - delimiters[8 /* AmpersandDelimited */] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28 /* DelimitersMask */]; - } function createBracketsMap() { var brackets = []; brackets[512 /* Braces */] = ["{", "}"]; @@ -72494,474 +73362,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - // Line separators - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - // Delimiters - ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited"; - ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited"; - ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited"; - ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited"; - ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask"; - ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma"; - // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - // Brackets/Braces - ListFormat[ListFormat["Braces"] = 512] = "Braces"; - ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis"; - ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets"; - ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets"; - ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask"; - ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined"; - ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty"; - ListFormat[ListFormat["Optional"] = 24576] = "Optional"; - // Other - ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; - ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; - ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; - ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; - // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "TupleTypeElements"; - ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; - ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; - ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; - ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; - ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; - ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; - ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; - ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments"; - ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans"; - ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements"; - ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements"; - ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; - ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; - ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "NamedImportsOrExportsElements"; - ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; - ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; - ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; - ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes"; - ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 24577] = "Decorators"; - ListFormat[ListFormat["TypeArguments"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - 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 changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - 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); }, - // Remove existing file info - onDeleteValue: removeExistingFileInfo, - // We will update in place instead of deleting existing value and adding new one - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - 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); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - 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); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - 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)]; - } - var seenFiles = ts.createMap(); - 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)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - 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]; - 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(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * @return {boolean} indicates if the shape signature has changed since last update. - */ - 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 = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Gets all files of the program excluding the default library file - */ - 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) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - 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 [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - // Changed if we had references - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - // If there are any new references that werent present previously there is change - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - // Otherwise its changed if there are more references previously than now - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - // Remove existing references - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - // add files referencing the removedFilePath, as changed files too - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - // Delete the entry for the removed file path - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.mapDefinedIter(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - }); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - 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(); - // Start with the paths this file was referenced by - var path = sourceFile.path; - 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); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - // Return array of values that needs emit - return ts.flatMapIter(seenFileNamesMap.values(), function (value) { return value; }); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); /// /// /// -/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; @@ -73155,23 +73559,31 @@ var ts; return errorMessage; } ts.formatDiagnostic = formatDiagnostic; - var redForegroundEscapeSequence = "\u001b[91m"; - var yellowForegroundEscapeSequence = "\u001b[93m"; - var blueForegroundEscapeSequence = "\u001b[93m"; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; function getCategoryFormat(category) { switch (category) { - case ts.DiagnosticCategory.Warning: return yellowForegroundEscapeSequence; - case ts.DiagnosticCategory.Error: return redForegroundEscapeSequence; - case ts.DiagnosticCategory.Message: return blueForegroundEscapeSequence; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; } } - function formatAndReset(text, formatStyle) { + /** @internal */ + function formatColorAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } + ts.formatColorAndReset = formatColorAndReset; function padLeft(s, length) { while (s.length < length) { s = " " + s; @@ -73184,9 +73596,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -73199,7 +73611,7 @@ var ts; // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -73208,11 +73620,11 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += redForegroundEscapeSequence; + context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += ForegroundColorEscapeSequences.Red; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. @@ -73229,19 +73641,25 @@ var ts; } context += resetEscapeSequence; } - output += host.getNewLine(); - output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + output += " - "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += formatColorAndReset(category, categoryColor); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); output += context; } output += host.getNewLine(); } - return output; + return output + host.getNewLine(); } ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; function flattenDiagnosticMessageText(messageText, newLine) { @@ -73509,7 +73927,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -73656,9 +74075,13 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.file, moduleName); - if (resolutionToFile) { - // module used to be resolved to file - ignore it + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); + var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. return false; } var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); @@ -73811,7 +74234,7 @@ var ts; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); @@ -73915,24 +74338,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } // Create the emit resolver outside of the "emitTime" tracking code below. That way @@ -73943,7 +74368,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -74306,6 +74731,7 @@ var ts; // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -74495,7 +74921,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -74622,7 +75048,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; + var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { @@ -74796,217 +75222,2408 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { - // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + if (ts.isArrayLiteralExpression(keyProps.initializer) && + keyProps.initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionPathsSyntax() { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + } + return ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile && options.configFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + } + return !!props.length; + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || + !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function checkAllDefined(names) { + ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); + return names; + } + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + 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 (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.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 (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // 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(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + if (map1 === undefined) { + return map2 === undefined; + } + if (map2 === undefined) { + return map1 === undefined; + } + // Has same size and every key is present in both maps + return map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState && oldState.referencedMap; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.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 = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var host; + var newProgram; + if (ts.isArray(newProgramOrRootNames)) { + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program) { + newProgram = undefined; + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = void 0; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + // If there is exception to read directories, dont cache the result and direct the calls to host + ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * 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, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + function addFileWatcher(host, file, cb) { + return host.watchFile(file, cb); + } + ts.addFileWatcher = addFileWatcher; + function addFileWatcherWithLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb); + } + ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; + function addFilePathWatcher(host, file, cb, path) { + return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); + } + ts.addFilePathWatcher = addFilePathWatcher; + function addFilePathWatcherWithLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb, path); + } + ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; + function addDirectoryWatcher(host, directory, cb, flags) { + var recursive = (flags & 1 /* Recursive */) !== 0; + return host.watchDirectory(directory, cb, recursive); + } + ts.addDirectoryWatcher = addDirectoryWatcher; + function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { + var info = "PathInfo: " + file; + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } + var watcher = addWatch(host, file, function (fileName, cbOptional1) { + var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; + log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); + var start = ts.timestamp(); + cb(fileName, cbOptional1, optional); + var elapsed = ts.timestamp() - start; + log(watcherCaption + "Elapsed: " + elapsed + "ms Trigger: " + fileName + optionalInfo + " " + info); + }, optional); + return { + close: function () { + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } + watcher.close(); + } + }; + } + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var allFilesHaveInvalidatedResolution = false; + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = rootDir && resolutionHost.toPath(rootDir); + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return collected && collected.has(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + clearPerDirectoryResolutions(); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + if (resolution.failedLookupLocations) { + if (existingResolution && existingResolution.failedLookupLocations) { + watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution); + } + else { + watchFailedLookupLocationOfResolution(resolution, 0); + } + } + else if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + 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 }; + } + var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); + var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch + if (isNodeModulesDirectory(dirPath)) { + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + } + // Use some ancestor of the root directory + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) { + var failedLookupLocations = resolution.failedLookupLocations; + var existingFailedLookupLocations = existingResolution.failedLookupLocations; + for (var index = 0; index < failedLookupLocations.length; index++) { + if (index === existingFailedLookupLocations.length) { + // Additional failed lookup locations, watch from this index + watchFailedLookupLocationOfResolution(resolution, index); + return; + } + else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) { + // Different failed lookup locations, + // Watch new resolution failed lookup locations from this index and + // stop watching existing resolutions from this index + watchFailedLookupLocationOfResolution(resolution, index); + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index); + return; + } + } + // All new failed lookup locations are already watched (and are same), + // Stop watching failed lookup locations of existing resolution after failed lookup locations length + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length); + } + function watchFailedLookupLocationOfResolution(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, 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 }); + } + } + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (resolution.failedLookupLocations) { + stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0); + } + } + function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + 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) { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // If the files are added to project root or node_modules directory, always run through the invalidation process + // Otherwise run through invalidation only if adding to the immediate directory + if (!allFilesHaveInvalidatedResolution && + dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + } + }, 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; } - // Cannot specify module gen that isn't amd or system with --out - if (outFile) { - if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + else { + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } } - // there has to be common source directory if user specified --outdir || --sourceRoot - // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted - if (options.outDir || // there is --outDir specified - options.sourceRoot || // there is --sourceRoot specified - options.mapRoot) { - // Precalculate and cache the common source directory - var dir = getCommonSourceDirectory(); - // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure - if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function createTypeRootsWatch(_typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // 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, + onDeleteValue: ts.closeFileWatcher + }); } - if (options.checkJs && !options.allowJs) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + else { + closeTypeRootsWatch(); } - if (options.emitDecoratorMetadata && - !options.experimentalDecorators) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + /** + * 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 = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { + if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + system.clearScreen(); + } + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onConfigFileDiagnostic = undefined; + host.onUnRecoverableConfigFileDiagnostic = undefined; + return result; + } + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + var cwd = host.getCurrentDirectory(); + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + return configParseResult; + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + // First get and report any syntactic errors. + var diagnostics = program.getSyntacticDiagnostics().slice(); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === 0) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); } - if (options.jsxFactory) { - if (options.reactNamespace) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); - } - if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; } + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + var _a; + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + trace: function (s) { return system.write(s); }, + onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; + var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onConfigFileDiagnostic: host.onConfigFileDiagnostic, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + if (configFileName && !rootFileNames) { + parseConfigFile(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + var writeLog = loggingEnabled ? trace : ts.noop; + var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; + var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; + var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, writeLog); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var newLine = updateNewLine(); + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: watchDirectory, + watchTypeRootsDirectory: watchDirectory, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : + (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : + (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + return builderProgram; + } + // Compile the program + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); + return builderProgram; + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function fileExists(fileName) { + var path = toPath(fileName); + var hostSourceFileInfo = sourceFilesCache.get(path); + if (hostSourceFileInfo !== undefined) { + return !ts.isString(hostSourceFileInfo); } - else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); - } - // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files - if (!options.noEmit && !options.suppressOutputPathCheck) { - var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createMap(); - ts.forEachEmittedFile(emitHost, function (emitFileNames) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); - verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); - }); + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (ts.isString(hostSourceFile)) { + return undefined; } - // Verify that all the emit files are unique and don't overwrite input files - function verifyEmitFilePath(emitFileName, emitFilesSeen) { - if (emitFileName) { - var emitFilePath = toPath(emitFileName); - // Report error if the output overwrites input file - if (filesByName.has(emitFilePath)) { - var chain_1; - if (!options.configFilePath) { - // The program is from either an inferred project or an external project - chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } - var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; - // Report error if multiple files write into same file - if (emitFilesSeen.has(emitFileKey)) { - // Already seen the same emit file - report error - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + else { + // There is no source file on host any more, close the watch, missing file paths will track it + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, hostSourceFile.version.toString()); + } + } + else { + var fileWatcher = void 0; + if (sourceFile) { + sourceFile.version = "1"; + fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: 1, fileWatcher: fileWatcher }); } else { - emitFilesSeen.set(emitFileKey, true); + sourceFilesCache.set(path, "0"); } } + return sourceFile; } - } - function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { - var pathProp = pathsSyntax_1[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer)) { - for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { - var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); - needCompilerDiagnostic = false; - } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); } } - } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; } } - function createDiagnosticForOptionPaths(onKey, key, message, arg0) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { - var pathProp = pathsSyntax_2[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer) && - createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { - needCompilerDiagnostic = false; + function removeSourceFile(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + resolutionCache.invalidateResolutionOfFile(path); } + sourceFilesCache.delete(path); } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || ts.isString(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (ts.isString(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + sourceFilesCache.delete(oldSourceFile.path); + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } - function getOptionPathsSyntax() { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); } - return ts.emptyArray; } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + timerToUpdateProgram = host.setTimeout(updateProgram, 250); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; } } - function getCompilerOptionsObjectLiteralSyntax() { - if (_compilerOptionsObjectLiteralSyntax === undefined) { - _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isObjectLiteralExpression(prop.initializer)) { - _compilerOptionsObjectLiteralSyntax = prop.initializer; - break; - } + function reloadFileNamesFromConfigFile() { + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { + host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + var configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); + rootFileNames = configParseResult.fileNames; + compilerOptions = configParseResult.options; + configFileSpecs = configParseResult.configFileSpecs; + configFileWildCardDirectories = configParseResult.wildcardDirectories; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile) { + // Update the cache + if (eventKind === ts.FileWatcherEventKind.Deleted) { + resolutionCache.invalidateResolutionOfFile(path); + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, (++hostSourceFile.version).toString()); + } + } + else { + // Deleted file created + if (ts.isString(hostSourceFile)) { + sourceFilesCache.delete(path); + } + else { + // file changed - just update the version + hostSourceFile.version++; } } } - return _compilerOptionsObjectLiteralSyntax; + // Update the program + scheduleProgramUpdate(); } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { - var props = ts.getPropertyAssignment(objectLiteral, key1, key2); - for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { - var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); } - return !!props.length; } - function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); - programDiagnostics.add(diag); + function watchDirectory(directory, cb, flags) { + return watchDirectoryWorker(host, directory, cb, flags, writeLog); } - } - ts.createProgram = createProgram; - /* @internal */ - /** - * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. - * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. - * This returns a diagnostic even if the module will be an untyped module. - */ - function getResolutionDiagnostic(options, _a) { - var extension = _a.extension; - switch (extension) { - case ".ts" /* Ts */: - case ".d.ts" /* Dts */: - // These are always allowed. - return undefined; - case ".tsx" /* Tsx */: - return needJsx(); - case ".jsx" /* Jsx */: - return needJsx() || needAllowJs(); - case ".js" /* Js */: - return needAllowJs(); + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); } - function needJsx() { - return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + removeSourceFile(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } } - function needAllowJs() { - return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + function watchConfigFileWildCardDirectories() { + if (configFileWildCardDirectories) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } } - } - ts.getResolutionDiagnostic = getResolutionDiagnostic; - function checkAllDefined(names) { - ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); - return names; - } - function getModuleNames(_a) { - var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; - var res = imports.map(function (i) { return i.text; }); - for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { - var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { - res.push(aug.text); + function watchWildcardDirectory(directory, flags) { + return watchDirectory(directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + var result = cachedDirectoryStructureHost && cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + // Instead of deleting the file, mark it as changed instead + // Many times node calls add/remove/file when watching directories recursively + var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); + if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { + hostSourceFile.version++; + } + else { + removeSourceFile(fileOrDirectoryPath); + } + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } } - // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. } - return res; } + ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); /// /// @@ -75153,12 +77770,14 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", + "esnext.promise": "lib.esnext.promise.d.ts", }), }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -75406,6 +78025,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -75696,19 +78322,19 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - var result = { + return { enable: typeAcquisition.enableAutoDiscovery, include: typeAcquisition.include || [], exclude: typeAcquisition.exclude || [] }; - return result; } return typeAcquisition; } @@ -76171,7 +78797,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean @@ -76200,7 +78826,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } @@ -76616,8 +79242,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - return options; + return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -76709,20 +79334,6 @@ var ts; * \/?$ # matches an optional trailing directory separator at the end of the string. */ var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - /** - * Tests for a path with multiple recursive directory wildcards. - * Matches **\** and **\a\**, but not **\a**b. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. - * (.*\/)? # optionally matches any number of characters followed by a directory separator. - * \*\* # matches a recursive directory wildcard "**" - * ($|\/) # matches either the end of the string or a directory separator. - */ - var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; /** * Tests for a path where .. appears after a recursive directory wildcard. * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* @@ -76891,9 +79502,6 @@ var ts; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } - else if (invalidMultipleRecursionPatterns.test(spec)) { - return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; - } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } @@ -77235,6 +79843,7 @@ var ts; ScriptElementKindModifier["ambientModifier"] = "declare"; ScriptElementKindModifier["staticModifier"] = "static"; ScriptElementKindModifier["abstractModifier"] = "abstract"; + ScriptElementKindModifier["optionalModifier"] = "optional"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); var ClassificationTypeNames; (function (ClassificationTypeNames) { @@ -77754,7 +80363,7 @@ var ts; return isCompletedNode(n.thenStatement, sourceFile); case 211 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || - hasChildOfKind(n, 25 /* SemicolonToken */); + hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); case 178 /* ArrayLiteralExpression */: case 176 /* ArrayBindingPattern */: case 181 /* ElementAccessExpression */: @@ -77777,11 +80386,9 @@ var ts; return isCompletedNode(n.statement, sourceFile); case 213 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - var hasWhileKeyword = findChildOfKind(n, 106 /* WhileKeyword */, sourceFile); - if (hasWhileKeyword) { - return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - } - return isCompletedNode(n.statement, sourceFile); + return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) + ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) + : isCompletedNode(n.statement, sourceFile); case 163 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); case 190 /* TypeOfExpression */: @@ -77811,7 +80418,6 @@ var ts; return true; } } - ts.isCompletedNode = isCompletedNode; /* * Checks if node ends with 'expectedLastToken'. * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. @@ -77851,7 +80457,7 @@ var ts; } ts.hasChildOfKind = hasChildOfKind; function findChildOfKind(n, kind, sourceFile) { - return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + return ts.find(n.getChildren(sourceFile), function (c) { return c.kind === kind; }); } ts.findChildOfKind = findChildOfKind; function findContainingList(node) { @@ -78042,8 +80648,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -78260,12 +80866,16 @@ var ts; ts.typeKeywords = [ 119 /* AnyKeyword */, 122 /* BooleanKeyword */, + 127 /* KeyOfKeyword */, 130 /* NeverKeyword */, + 95 /* NullKeyword */, 133 /* NumberKeyword */, 134 /* ObjectKeyword */, 136 /* StringKeyword */, 137 /* SymbolKeyword */, 105 /* VoidKeyword */, + 139 /* UndefinedKeyword */, + 140 /* UniqueKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -78286,6 +80896,28 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; + /** Add a value to a set, and return true if it wasn't already present. */ + function addToSeen(seen, key) { + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, true); + return true; + } + ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -78300,6 +80932,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -78309,8 +80942,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -78431,14 +81074,17 @@ var ts; /** * The default is CRLF. */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; + /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -78451,35 +81097,23 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { - return ts.getTextOfIdentifierOrLiteral(location); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && @@ -78493,12 +81127,16 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -78525,57 +81163,6 @@ var ts; return position; } ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition; - function getOpenBrace(constructor, sourceFile) { - // First token is the open curly, this is where we want to put the 'super' call. - return constructor.body.getFirstToken(sourceFile); - } - ts.getOpenBrace = getOpenBrace; - function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); - } - ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; - function getSourceFileImportLocation(_a) { - var text = _a.text; - var shebang = ts.getShebang(text); - var position = 0; - if (shebang !== undefined) { - position = shebang.length; - advancePastLineBreak(); - } - // For a source file, it is possible there are detached comments we should not skip - var ranges = ts.getLeadingCommentRanges(text, position); - if (!ranges) - return position; - // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { - position = ranges[0].end; - advancePastLineBreak(); - ranges = ranges.slice(1); - } - // As well as any triple slash references - for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { - var range = ranges_1[_i]; - if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { - position = range.end; - advancePastLineBreak(); - continue; - } - break; - } - return position; - function advancePastLineBreak() { - if (position < text.length) { - var charCode = text.charCodeAt(position); - if (ts.isLineBreak(charCode)) { - position++; - if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { - position++; - } - } - } - } - } - ts.getSourceFileImportLocation = getSourceFileImportLocation; /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -78607,6 +81194,10 @@ var ts; return visited; } ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + } + ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ @@ -78880,7 +81471,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -78889,8 +81480,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -79213,32 +81804,39 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. continue; - } - // for the ||||||| and ======== markers, add a comment for the first line, - // and then lex all subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); } } } @@ -79400,7 +81998,7 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } - // Special case < and > If they appear in a generic context they are punctuation, + // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then @@ -79510,11 +82108,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -79594,7 +82192,7 @@ var ts; continue; } var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); - if (!foundFiles.get(foundFileName)) { + if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } @@ -79629,37 +82227,20 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; + for (var path in paths) { var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); } } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } - } - }; - for (var path in paths) { - _loop_6(path); } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -79671,50 +82252,60 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + } + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - if (matches) { - var result = []; - // Trim away prefix and suffix - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + if (!host.readDirectory) { + return undefined; } - return undefined; + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + var directories = tryGetDirectories(host, baseDirectory); + // Trim away prefix and suffix + return ts.mapDefined(ts.concatenate(matches, directories), function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module @@ -79786,10 +82377,12 @@ var ts; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -79801,31 +82394,38 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -79963,26 +82563,55 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } + if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) + && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { + return getLabelCompletionAtPosition(contextToken.parent); } var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); 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, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { + switch (completionData.kind) { + case 0 /* Data */: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1 /* JsDocTagName */: + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2 /* JsDocTag */: + // If the current position is a jsDoc tag, only tags should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3 /* JsDocParameterName */: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
completion list at "1" will contain "div" with type any + // var x =
+ // The completion list at "1" will contain "div" with type any var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -79992,37 +82621,37 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - // If the current position is a jsDoc tag name, only tag names should be provided for completion - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - // If the current position is a jsDoc tag, only tags should be provided for completion - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, 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, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if // - this is not a member completion list (all the keywords) // - other filters are enabled in required scenario so add those keywords + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -80030,14 +82659,9 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: "1" @@ -80045,12 +82669,30 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + var insertText; + var replacementSpan; + if (includeInsertTextCompletions) { + if (origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + // TODO: GH#20619 Use configured quote style + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + } + } + if (insertText !== undefined && !includeInsertTextCompletions) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -80061,13 +82703,15 @@ var ts; // Use a 'sortText' of 0' so that all symbol completion entries come before any other // entries (like JavaScript identifier entries). return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -80078,103 +82722,119 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); - if (symbols) { - for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { - var symbol = symbols_5[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); - if (!entry) { - continue; - } - var name = entry.name; - if (uniques.has(name)) { - continue; - } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { - uniques.set(name, true); - } - entries.push(entry); + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; + var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + if (!entry) { + continue; + } + var name = entry.name; + if (uniques.has(name)) { + continue; + } + // Latter case tests whether this is a global variable. + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + uniques.set(name, true); } + entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniques; } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || node.kind !== 9 /* StringLiteral */) { - return undefined; - } - if (node.parent.kind === 265 /* PropertyAssignment */ && - node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && - node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ - || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (isEqualityExpression(node.parent)) { - // Get completions from the type of the other operand - // i.e. switch (a) { - // case '/*completion position*/' - // } - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker); - } - else if (ts.isCaseOrDefaultClause(node.parent)) { - // Get completions from the type of the switch expression - // i.e. x === '/*completion position' - return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.parent.parent.expression), typeChecker); + function getLabelCompletionAtPosition(node) { + var entries = getLabelStatementCompletions(node); + if (entries.length) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + } + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174 /* LiteralType */: + switch (node.parent.parent.kind) { + case 160 /* TypeReference */: + // TODO: GH#21168 + return undefined; + case 172 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265 /* PropertyAssignment */: + if (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && + node.parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181 /* ElementAccessExpression */: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 249 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" - return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker); + return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); } } function pathCompletionsInfo(entries) { @@ -80188,11 +82848,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80212,11 +82872,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccess(node, typeChecker, target, log) { - var type = typeChecker.getTypeAtLocation(node.expression); + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80233,6 +82892,30 @@ var ts; } return undefined; } + function getLabelStatementCompletions(node) { + var entries = []; + var uniques = ts.createMap(); + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (ts.isLabeledStatement(current)) { + var name = current.label.text; + if (!uniques.has(name)) { + uniques.set(name, true); + entries.push({ + name: name, + kindModifiers: "" /* none */, + kind: "label" /* label */, + sortText: "0" + }); + } + } + current = current.parent; + } + return entries; + } function addStringLiteralCompletionsFromType(type, result, typeChecker, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } if (type && type.flags & 32768 /* TypeParameter */) { @@ -80262,29 +82945,33 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; } + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; // 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.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap } : { type: "none" }; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.name === "default" ? ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) + : symbol.name; } - function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + var typeChecker = program.getTypeChecker(); var name = entryId.name; // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); @@ -80292,26 +82979,26 @@ var ts; case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1 /* JsDocTagName */: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2 /* JsDocTag */: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, typeChecker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; } case "none": { // Didn't find a symbol with this name. See if we can find a keyword instead. - if (ts.some(getKeywordCompletions(0 /* None */), function (c) { return c.name === name; })) { + if (allKeywordsCompletions().some(function (c) { return c.name === name; })) { return { name: name, kind: "keyword" /* keyword */, @@ -80328,28 +83015,30 @@ var ts; } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, checker, host, compilerOptions, sourceFile, formatContext, getCanonicalFileName, allSourceFiles) { + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo && symbolOriginInfo.type === "export" + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); ts.Debug.assert(ts.contains(moduleSymbols, moduleSymbol)); - var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; + var sourceDisplay = [ts.textPart(ts.first(ts.codefix.getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host)))]; var codeActions = ts.codefix.getCodeActionForImport(moduleSymbols, { host: host, + program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), getCanonicalFileName: getCanonicalFileName, - symbolToken: undefined, + symbolToken: ts.tryCast(previousToken, ts.isIdentifier), kind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, - }); + }).slice(0, 1); // Only take the first code action return { sourceDisplay: sourceDisplay, codeActions: codeActions }; } function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { @@ -80369,14 +83058,70 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; - function getRecommendedCompletion(currentToken, checker /*, symbolToOriginInfoMap: SymbolOriginInfoMap*/) { - var ty = checker.getContextualType(currentToken); + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */ + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); + function getRecommendedCompletion(currentToken, checker) { + var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; // Don't include make a recommended completion for an abstract class return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) ? getFirstSymbolInChain(symbol, currentToken, checker) : undefined; } + function getContextualType(currentToken, checker) { + var parent = currentToken.parent; + switch (currentToken.kind) { + case 71 /* Identifier */: + return getContextualTypeFromParent(currentToken, checker); + case 58 /* EqualsToken */: + return ts.isVariableDeclaration(parent) ? checker.getContextualType(parent.initializer) : + ts.isBinaryExpression(parent) ? checker.getTypeAtLocation(parent.left) : undefined; + case 94 /* NewKeyword */: + return checker.getContextualType(parent); + case 73 /* CaseKeyword */: + return getSwitchedType(ts.cast(currentToken.parent, ts.isCaseClause), checker); + default: + return isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + // completion at `x ===/**/` should be for the right side + ? checker.getTypeAtLocation(parent.left) + : checker.getContextualType(currentToken); + } + } + function getContextualTypeFromParent(node, checker) { + var parent = node.parent; + switch (parent.kind) { + case 183 /* NewExpression */: + return checker.getContextualType(parent); + case 195 /* BinaryExpression */: { + var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case 261 /* CaseClause */: + return parent.expression === node ? getSwitchedType(parent, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + function getSwitchedType(caseClause, checker) { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { var chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ 67108863 /* All */, /*useOnlyExternalAliasing*/ false); if (chain) @@ -80387,7 +83132,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -80402,7 +83146,7 @@ var ts; if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } else { // When completion is requested without "@", we will have check to make sure that @@ -80423,7 +83167,7 @@ var ts; // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 /* JsDocTag */ }; } } } @@ -80433,7 +83177,7 @@ var ts; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); @@ -80446,24 +83190,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3 /* JsDocParameterName */, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0 /* None */, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - }; - } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available @@ -80488,9 +83217,11 @@ var ts; // Also determine whether we are trying to complete with members of that node // or attributes of a JSX tag. var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; + var isJsxInitializer = false; var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location @@ -80500,18 +83231,19 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 180 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144 /* QualifiedName */: + node = parent.left; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; } } else if (sourceFile.languageVariant === 1 /* JSX */) { @@ -80543,14 +83275,15 @@ var ts; location = contextToken; } break; + case 257 /* JsxAttribute */: + isJsxInitializer = previousToken.kind === 58 /* EqualsToken */; + break; } } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; var symbols = []; var symbolToOriginInfoMap = []; @@ -80565,8 +83298,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -80574,8 +83306,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -80586,8 +83317,8 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - var recommendedCompletion = getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion }; + var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284 /* JSDocParameterTag */: @@ -80600,9 +83331,7 @@ var ts; } function getTypeScriptMemberSymbols() { // Right of dot member completion list - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2 /* PropertyAccess */; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); @@ -80647,10 +83376,9 @@ var ts; symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true)); } else { - // Filter private properties for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (typeChecker.isValidPropertyAccessForCompletions((node.parent), type, symbol)) { symbols.push(symbol); } } @@ -80671,13 +83399,16 @@ var ts; } if (tryGetConstructorLikeCompletionContainer(contextToken)) { // no members, only keywords - isMemberCompletion = false; + completionKind = 5 /* None */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter keywordFilters = 2 /* ConstructorParameterKeywords */; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3 /* FunctionLikeBodyKeywords */; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -80690,14 +83421,14 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return true; } } } // Get all entities in the current scope. - isMemberCompletion = false; + completionKind = 5 /* None */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -80731,40 +83462,55 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 /* SourceFile */ || - scopeNode.kind === 197 /* TemplateExpression */ || - scopeNode.kind === 260 /* JsxExpression */ || - scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1 /* Global */; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (options.includeInsertTextCompletions && scopeNode.kind !== 269 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269 /* SourceFile */: + case 197 /* TemplateExpression */: + case 260 /* JsxExpression */: + case 208 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { + var isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + if (isTypeCompletion) + keywordFilters = 4 /* TypeKeywords */; 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)) { return true; } - // This is an alias, follow what it aliases - if (symbol && symbol.flags & 2097152 /* Alias */) { - symbol = typeChecker.getAliasedSymbol(symbol); - } + symbol = ts.skipAlias(symbol, typeChecker); // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & 1920 /* Namespace */); } - if (insideJsDocTagTypeExpression || - (!isContextTokenValueLocation(contextToken) && - (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + if (isTypeCompletion) { // Its a type, but you can reach it by namespace.type as well return symbolCanBeReferencedAtTypeLocation(symbol); } @@ -80794,6 +83540,7 @@ var ts; return parentKind === 203 /* AsExpression */; } } + return false; } function symbolCanBeReferencedAtTypeLocation(symbol) { symbol = symbol.exportSymbol || symbol; @@ -80814,27 +83561,21 @@ var ts; ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; - var name = symbol.name; // Don't add a completion for a re-export, only for the original. - // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } - var isDefaultExport = name === "default"; + var isDefaultExport = symbol.name === "default" /* Default */; if (isDefaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(symbol); - if (localSymbol) { - symbol = localSymbol; - name = localSymbol.name; - } - else { - name = ts.codefix.moduleSymbolToValidIdentifier(moduleSymbol, target); - } + symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - if (stringContainsCharactersInOrder(name.toLowerCase(), tokenTextLowerCase)) { + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -80972,8 +83713,7 @@ var ts; */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { @@ -80998,7 +83738,7 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 217 /* ForOfStatement */; if (!canGetType && rootDeclaration.kind === 147 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); @@ -81046,7 +83786,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -81063,7 +83803,7 @@ var ts; */ function getGetClassLikeCompletionSymbols(classLikeDeclaration) { // We're looking up possible property names from parent type. - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements @@ -81214,6 +83954,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -81383,7 +84138,10 @@ var ts; case "yield": return true; } - return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + return ts.isDeclarationName(contextToken) + && !ts.isJsxAttribute(contextToken.parent) + // Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`. + && !(ts.isClassLike(contextToken.parent) && position > previousToken.end); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; @@ -81416,9 +84174,9 @@ var ts; existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" /* Default */; }); } - return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" /* Default */ && !existingImportsOrExports.get(e.escapedName); }); } /** * Filters out completion suggestions for named imports or exports. @@ -81542,88 +84300,69 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + // 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) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { return undefined; - // 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 (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; - } } - // If the symbol is for a member of an object type and is the internal name of an ES - // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - if (symbol.flags & 106500 /* ClassMember */) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 /* _ */ && - escapedName.charCodeAt(1) === 95 /* _ */ && - escapedName.charCodeAt(2) === 64 /* at */) { + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 3 /* MemberLike */: return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - // TODO: GH#18169 - return allowStringLiteral ? JSON.stringify(name) : undefined; + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + case 5 /* None */: + case 1 /* Global */: + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - return name; } // A cache of completion entries for keywords, these do not change between sessions var _keywordCompletions = []; - function getKeywordCompletions(keywordFilter) { - var completions = _keywordCompletions[keywordFilter]; - if (completions) { - return completions; + var allKeywordsCompletions = ts.memoize(function () { + var res = []; + for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { + res.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); } - return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); - function generateKeywordCompletions(keywordFilter) { + return res; + }); + function getKeywordCompletions(keywordFilter) { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { + var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - return getAllKeywordCompletions(); + // "undefined" is a global variable, so don't need a keyword completion for it. + return kind !== 139 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: - return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + return isClassMemberCompletionKeyword(kind); case 2 /* ConstructorParameterKeywords */: - return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); - } - } - function getAllKeywordCompletions() { - var allKeywordsCompletions = []; - for (var i = 72 /* FirstKeyword */; i <= 143 /* LastKeyword */; i++) { - // "undefined" is a global variable, so don't need a keyword completion for it. - if (i === 139 /* UndefinedKeyword */) - continue; - allKeywordsCompletions.push({ - name: ts.tokenToString(i), - kind: "keyword" /* keyword */, - kindModifiers: "" /* none */, - sortText: "0" - }); + return isConstructorParameterCompletionKeyword(kind); + case 3 /* FunctionLikeBodyKeywords */: + return isFunctionLikeBodyCompletionKeyword(kind); + case 4 /* TypeKeywords */: + return ts.isTypeKeyword(kind); + default: + return ts.Debug.assertNever(keywordFilter); } - return allKeywordsCompletions; - } - function getFilteredKeywordCompletions(filterFn) { - return ts.filter(getKeywordCompletions(0 /* None */), function (entry) { return filterFn(entry.name); }); - } + })); } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -81655,14 +84394,32 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } - function isEqualityExpression(node) { - return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + case 117 /* AbstractKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + case 139 /* UndefinedKeyword */: + return false; + } + return true; } function isEqualityOperatorKind(kind) { - return kind === 32 /* EqualsEqualsToken */ || - kind === 33 /* ExclamationEqualsToken */ || - kind === 34 /* EqualsEqualsEqualsToken */ || - kind === 35 /* ExclamationEqualsEqualsToken */; + switch (kind) { + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + return true; + default: + return false; + } } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { @@ -81696,8 +84453,7 @@ var ts; } /** * Gets all properties on a type, but if that type is a union of several types, - * tries to only include those types which declare properties, not methods. - * This ensures that we don't try providing completions for all the methods on e.g. Array. + * excludes array-like types or callable/constructable types. */ function getPropertiesForCompletion(type, checker, isForAccess) { if (!(type.flags & 131072 /* Union */)) { @@ -81719,11 +84475,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Note that getTouchingWord indicates failure by returning the sourceFile node. - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { @@ -81732,7 +84484,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -81742,8 +84494,8 @@ var ts; kind: "none" /* none */ }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -82538,7 +85290,7 @@ var ts; } function isNameMatch(name) { // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports - return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default"; + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; } } /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ @@ -82752,7 +85504,7 @@ var ts; // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) var importedName = symbolName(importedSymbol); - if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { + if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } @@ -82816,7 +85568,7 @@ var ts; } FindAllReferences.getExportInfo = getExportInfo; function symbolName(symbol) { - if (symbol.escapedName !== "default") { + if (symbol.escapedName !== "default" /* Default */) { return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { @@ -82826,7 +85578,7 @@ var ts; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { - // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -82872,30 +85624,23 @@ var ts; FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { var referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position); - if (!referencedSymbols || !referencedSymbols.length) { - return undefined; - } - var out = []; var checker = program.getTypeChecker(); - for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { - var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references; + return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { + var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - if (definition) { - out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }); - } - } - return out; + return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) }; + }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { // A node in a JSDoc comment can't have an implementation anyway. var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269 /* SourceFile */) { return undefined; } @@ -82915,7 +85660,7 @@ var ts; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -82923,14 +85668,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -82941,8 +85686,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_3 = def.node; var _a = getDefinitionKindAndDisplayParts(symbol, node_3, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_5 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_3, name: name_5, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_3, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_4 = def.node; @@ -82950,8 +85695,8 @@ var ts; } case "keyword": { var node_5 = def.node; - var name_6 = ts.tokenToString(node_5.kind); - return { node: node_5, name: name_6, kind: "keyword" /* keyword */, displayParts: [{ text: name_6, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_5.kind); + return { node: node_5, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case "this": { var node_6 = def.node; @@ -83069,10 +85814,11 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269 /* SourceFile */) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -83085,11 +85831,7 @@ var ts; // Could not find a symbol e.g. unknown identifier if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. - if (!options.implementations && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - // Can't have references to something that we have no symbol for. - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -83098,7 +85840,7 @@ var ts; } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; function isModuleReferenceLocation(node) { - if (node.kind !== 9 /* StringLiteral */) { + if (node.kind !== 9 /* StringLiteral */ && node.kind !== 13 /* NoSubstitutionTemplateLiteral */) { return false; } switch (node.parent.kind) { @@ -83173,11 +85915,11 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); // Compute the meaning from the location and the symbol it references 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 state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); if (node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, node, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); @@ -83201,8 +85943,22 @@ var ts; } return result; } + function getSpecialSearchKind(node) { + switch (node.kind) { + case 123 /* ConstructorKeyword */: + return 1 /* Constructor */; + case 71 /* Identifier */: + if (ts.isClassLike(node.parent)) { + ts.Debug.assert(node.parent.name === node); + return 2 /* Class */; + } + // falls through + default: + return 0 /* None */; + } + } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -83211,18 +85967,29 @@ var ts; // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. return checker.getImmediateAliasedSymbol(symbol); } - return symbol; - } + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; + } + var SpecialSearchKind; + (function (SpecialSearchKind) { + SpecialSearchKind[SpecialSearchKind["None"] = 0] = "None"; + SpecialSearchKind[SpecialSearchKind["Constructor"] = 1] = "Constructor"; + SpecialSearchKind[SpecialSearchKind["Class"] = 2] = "Class"; + })(SpecialSearchKind || (SpecialSearchKind = {})); /** * Holds all state needed for the finding references. * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { function State(sourceFiles, - /** True if we're searching for constructor references. */ - isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; - this.isForConstructor = isForConstructor; + this.specialSearchKind = specialSearchKind; this.checker = checker; this.cancellationToken = cancellationToken; this.searchMeaning = searchMeaning; @@ -83264,6 +86031,9 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); @@ -83576,11 +86346,18 @@ var ts; getReferenceForShorthandProperty(referenceSymbol, search, state); return; } - if (state.isForConstructor) { - findConstructorReferences(referenceLocation, sourceFile, search, state); - } - else { - addReference(referenceLocation, relatedSymbol, search.location, state); + switch (state.specialSearchKind) { + case 0 /* None */: + addReference(referenceLocation, relatedSymbol, search.location, state); + break; + case 1 /* Constructor */: + addConstructorReferences(referenceLocation, sourceFile, search, state); + break; + case 2 /* Class */: + addClassStaticThisReferences(referenceLocation, search, state); + break; + default: + ts.Debug.assertNever(state.specialSearchKind); } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } @@ -83679,22 +86456,46 @@ var ts; } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ - function findConstructorReferences(referenceLocation, sourceFile, search, state) { + function addConstructorReferences(referenceLocation, sourceFile, search, state) { if (ts.isNewExpressionTarget(referenceLocation)) { addReference(referenceLocation, search.symbol, search.location, state); } - var pusher = state.referenceAdder(search.symbol, search.location); + var pusher = function () { return state.referenceAdder(search.symbol, search.location); }; if (ts.isClassLike(referenceLocation.parent)) { ts.Debug.assert(referenceLocation.parent.name === referenceLocation); // This is the class declaration containing the constructor. - findOwnConstructorReferences(search.symbol, sourceFile, pusher); + findOwnConstructorReferences(search.symbol, sourceFile, pusher()); } else { // If this class appears in `extends C`, then the extending class' "super" calls are references. var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); - if (classExtending && ts.isClassLike(classExtending)) { - findSuperConstructorAccesses(classExtending, pusher); + if (classExtending) { + findSuperConstructorAccesses(classExtending, pusher()); + } + } + } + function addClassStaticThisReferences(referenceLocation, search, state) { + addReference(referenceLocation, search.symbol, search.location, state); + if (ts.isClassLike(referenceLocation.parent)) { + ts.Debug.assert(referenceLocation.parent.name === referenceLocation); + // This is the class declaration. + addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol, search.location)); + } + } + function addStaticThisReferences(classLike, pusher) { + for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { + continue; } + member.body.forEachChild(function cb(node) { + if (node.kind === 99 /* ThisKeyword */) { + pusher(node); + } + else if (!ts.isFunctionLike(node)) { + node.forEachChild(cb); + } + }); } } function getPropertyAccessExpressionFromRightHandSide(node) { @@ -83768,7 +86569,7 @@ var ts; var containingTypeReference = getContainingTypeReference(refNode); if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { var parent = containingTypeReference.parent; - if (ts.isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) { + if (ts.hasType(parent) && parent.type === containingTypeReference && ts.hasInitializer(parent) && isImplementationExpression(parent.initializer)) { addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { @@ -84063,7 +86864,7 @@ var ts; // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol, location, checker, implementations) { // The search set contains at least the current symbol - var result = [symbol]; + var result = []; var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { // If the location is name of property symbol from object literal destructuring pattern @@ -84078,9 +86879,10 @@ var ts; // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - ts.addRange(result, checker.getRootSymbols(contextualSymbol)); - }); + for (var _i = 0, _a = getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker); _i < _a.length; _i++) { + var contextualSymbol = _a[_i]; + addRootSymbols(contextualSymbol); + } /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -84116,9 +86918,7 @@ var ts; // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { var rootSymbol = _a[_i]; - if (rootSymbol !== sym) { - result.push(rootSymbol); - } + result.push(rootSymbol); // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); @@ -84201,9 +87001,7 @@ var ts; // compare to our searchSymbol var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); if (containingObjectLiteralElement) { - var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) { - return ts.find(checker.getRootSymbols(contextualSymbol), search.includes); - }); + var contextualSymbol = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), findRootSymbol); if (contextualSymbol) { return contextualSymbol; } @@ -84229,7 +87027,7 @@ var ts; function findRootSymbol(sym) { // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) // Or a union property, use its underlying unioned symbols - return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { // if it is in the list, then we are done if (search.includes(rootSymbol)) { return rootSymbol; @@ -84239,11 +87037,11 @@ var ts; // parent symbol if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { // Parents will only be defined if implementations is true - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })) { return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); return ts.find(result, search.includes); } return undefined; @@ -84263,26 +87061,11 @@ var ts; } /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { - var objectLiteral = node.parent; - var contextualType = checker.getContextualType(objectLiteral); + var contextualType = checker.getContextualType(node.parent); var name = getNameFromObjectLiteralElement(node); - if (name && contextualType) { - var result_5 = []; - var symbol = contextualType.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - if (contextualType.flags & 131072 /* Union */) { - ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name); - if (symbol) { - result_5.push(symbol); - } - }); - } - return result_5; - } - return undefined; + var symbol = contextualType && name && contextualType.getProperty(name); + return symbol ? [symbol] : + contextualType && contextualType.flags & 131072 /* Union */ ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -84317,14 +87100,12 @@ var ts; if (!node) { return false; } - else if (ts.isVariableLike(node)) { - if (node.initializer) { - return true; - } - else if (node.kind === 227 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } + else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { + return true; + } + else if (node.kind === 227 /* VariableDeclaration */) { + var parentStatement = getParentStatementOfVariableDeclaration(node); + return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); } else if (ts.isFunctionLike(node)) { return !!node.body || ts.hasModifier(node, 2 /* Ambient */); @@ -84408,21 +87189,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - // Might still be on jsdoc, so keep looking. - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { @@ -84510,6 +87279,21 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -84517,26 +87301,14 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_6 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_6, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_6; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -84580,59 +87352,29 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 123 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + if (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */ && symbol.flags & 32 /* Class */) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; - } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; + return undefined; } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -84682,6 +87424,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -84720,7 +87463,6 @@ var ts; (function (ts) { var JsDoc; (function (JsDoc) { - var singleLineTemplate = { newText: "/** */", caretOffset: 3 }; var jsDocTagNames = [ "augments", "author", @@ -84774,18 +87516,29 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289 /* JSDocPropertyTag */: + return [declaration]; + case 288 /* JSDocTypedefTag */: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; @@ -84816,10 +87569,13 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } /** @@ -84830,7 +87586,7 @@ var ts; function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -84911,9 +87667,16 @@ var ts; /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. - * Invalid positions are - * - within comments, strings (including template literals and regex), and JSXText - * - within a token + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * - interface declarations + * - method signatures + * - type alias declarations * * Hosts should ideally check that: * - The line is all whitespace up to 'position' before performing the insertion. @@ -84936,29 +87699,35 @@ var ts; } var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); if (!commentOwnerInfo) { - // if climbing the tree did not find a declaration with parameters, complete to a single line comment - return singleLineTemplate; + return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.kind === 10 /* JsxText */) { + if (commentOwner.getStart() < position) { return undefined; } - if (commentOwner.getStart() < position || parameters.length === 0) { - // if climbing the tree found a declaration with parameters but the request was made inside it - // or if there are no parameters, complete to a single line comment - return singleLineTemplate; + if (!parameters || parameters.length === 0) { + // if there are no parameters, just complete to a single line JSDoc comment + var singleLineResult = "/** */"; + return { newText: singleLineResult, caretOffset: 3 }; } var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = parameters.map(function (_a, i) { - var name = _a.name; - var nameText = ts.isIdentifier(name) ? name.text : "param" + i; - var type = isJavaScriptFile ? "{any} " : ""; - return indentationStr + " * @param " + type + nameText + newLine; - }).join(""); + var docParams = ""; + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 /* Identifier */ ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } + } // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -84984,16 +87753,28 @@ var ts; case 151 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; + case 230 /* ClassDeclaration */: + case 231 /* InterfaceDeclaration */: + case 149 /* PropertySignature */: + case 233 /* EnumDeclaration */: + case 268 /* EnumMember */: + case 232 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner }; case 209 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return parameters_1 ? { commentOwner: commentOwner, parameters: parameters_1 } : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; } case 269 /* SourceFile */: return undefined; + case 234 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 234 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 195 /* BinaryExpression */: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { @@ -85002,10 +87783,6 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } - case 10 /* JsxText */: { - var parameters_3 = ts.emptyArray; - return { commentOwner: commentOwner, parameters: parameters_3 }; - } } } } @@ -85211,8 +87988,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_7.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -85343,7 +88120,7 @@ var ts; if (!shouldKeepItem(declaration, checker)) { continue; } - // It was a match! If the pattern has dots in it, then also see if the + // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. var containerMatches = matches; if (patternMatcher.patternContainsDots) { @@ -85372,8 +88149,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -85442,8 +88219,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -87088,7 +89865,7 @@ var ts; // import "mod"; // import d from "mod" // import {a as A } from "mod"; - // import * as NS from "mod" + // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); // import("mod"); @@ -87188,9 +89965,16 @@ var ts; symbol.parent.flags & 1536 /* Module */) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9 /* StringLiteral */) { @@ -87424,7 +90208,7 @@ var ts; function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may // also just have nodes without commas. For example "Foo(a b c)" will have 3 - // args without commas. We want to find what index we're at. So we count + // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. // @@ -87450,12 +90234,12 @@ var ts; // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there - // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // is a small subtlety. If you have "Foo(a,)", then the child list will just have // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); @@ -87476,9 +90260,11 @@ var ts; // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // + // tslint:disable no-double-space // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -87525,9 +90311,8 @@ var ts; // Otherwise, we will not show signature help past the expression. // For example, // - // ` ${ 1 + 1 foo(10) - // | | - // + // ` ${ 1 + 1 foo(10) + // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 197 /* TemplateExpression */) { @@ -87569,6 +90354,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -87584,14 +90370,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -87599,7 +90391,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -87620,7 +90420,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -87631,7 +90432,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -87746,13 +90548,17 @@ var ts; return "" /* unknown */; } function getSymbolModifiers(symbol) { - return symbol && symbol.declarations && symbol.declarations.length > 0 + var nodeModifiers = symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) : "" /* none */; + var symbolModifiers = symbol && symbol.flags & 16777216 /* Optional */ ? + "optional" /* optionalModifier */ + : "" /* none */; + return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -87762,6 +90568,8 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var printer; + var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -87829,14 +90637,14 @@ var ts; displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -87877,6 +90685,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) @@ -87892,14 +90701,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -87907,10 +90716,10 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); @@ -87920,7 +90729,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); @@ -87928,7 +90737,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); @@ -87956,12 +90765,12 @@ var ts; else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example - // type list = T[]; // Both T will go through same code path + // type list = T[]; // Both T will go through same code path addInPrefix(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -87986,7 +90795,23 @@ var ts; } } if (symbolFlags & 2097152 /* Alias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -88032,7 +90857,7 @@ var ts; if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); } else { @@ -88049,7 +90874,8 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -88100,26 +90926,45 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias" /* alias */); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92 /* InKeyword */)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); - if (!ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { + if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -88142,7 +90987,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88157,7 +91002,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -88671,8 +91517,12 @@ var ts; for (var token = 0 /* FirstToken */; token <= 143 /* LastToken */; token++) { allTokens.push(token); } - function anyTokenExcept(token) { - return { tokens: allTokens.filter(function (t) { return t !== token; }), isSpecific: false }; + function anyTokenExcept() { + var tokens = []; + for (var _i = 0; _i < arguments.length; _i++) { + tokens[_i] = arguments[_i]; + } + return { tokens: allTokens.filter(function (t) { return !tokens.some(function (t2) { return t2 === t; }); }), isSpecific: false }; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); @@ -88702,7 +91552,7 @@ var ts; // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator @@ -88720,17 +91570,17 @@ var ts; rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace + // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 44 /* MinusMinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 38 /* MinusToken */, 38 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterSubtractWhenFollowedByPredecrement", 38 /* MinusToken */, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), - rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [22 /* CloseBracketToken */, 26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceAfterCloseBrace", 18 /* CloseBraceToken */, [26 /* CommaToken */, 25 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // For functions and control block place } on a new line [multi-line rule] rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 18 /* CloseBraceToken */, [isMultilineBlockContext], 4 /* NewLine */), // Space/new line after }. @@ -88817,7 +91667,7 @@ var ts; rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), // decorators - rule("SpaceBeforeAt", anyToken, 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), // Insert space after @ in decorator rule("SpaceAfterDecorator", anyToken, [ @@ -88843,8 +91693,8 @@ var ts; // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses rule("SpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterConstructor", 123 /* ConstructorKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 8 /* Delete */), - rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext, isNextTokenNotCloseBracket], 2 /* Space */), - rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementContext], 8 /* Delete */), + rule("SpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 2 /* Space */), + rule("NoSpaceAfterComma", 26 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 8 /* Delete */), // Insert space after function keyword for anonymous functions rule("SpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 2 /* Space */), rule("NoSpaceAfterAnonymousFunctionKeyword", 89 /* FunctionKeyword */, 19 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 8 /* Delete */), @@ -88899,8 +91749,10 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; - // These rules are lower in priority than user-configurable + // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ // Space after keyword but not before ; or : or ? rule("NoSpaceBeforeSemicolon", anyToken, 25 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), @@ -88908,13 +91760,13 @@ var ts; rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 2 /* Space */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 26 /* CommaToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), - // No space before and after indexer - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(120 /* AsyncKeyword */, 73 /* CaseKeyword */), 21 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterCloseBracket", 22 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 8 /* Delete */), rule("SpaceAfterSemicolon", 25 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementContext, isNotForContext], 2 /* Space */), + rule("SpaceBetweenStatements", [20 /* CloseParenToken */, 81 /* DoKeyword */, 82 /* ElseKeyword */, 73 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 2 /* Space */), // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryFinally", [102 /* TryKeyword */, 87 /* FinallyKeyword */], 17 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), ]; @@ -89004,6 +91856,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 /* PropertyDeclaration */ || + contextKind === 149 /* PropertySignature */ || + contextKind === 147 /* Parameter */ || + contextKind === 227 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196 /* ConditionalExpression */; } @@ -89149,11 +92012,11 @@ var ts; function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } - function isNonJsxElementContext(context) { - return context.contextNode.kind !== 250 /* JsxElement */; + function isNonJsxElementOrFragmentContext(context) { + return context.contextNode.kind !== 250 /* JsxElement */ && context.contextNode.kind !== 254 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 260 /* JsxExpression */; + return context.contextNode.kind === 260 /* JsxExpression */ || context.contextNode.kind === 259 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { return context.nextTokenParent.kind === 257 /* JsxAttribute */; @@ -89675,29 +92538,32 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1 /* Unknown */) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -89731,67 +92597,55 @@ var ts; case 18 /* CloseBraceToken */: case 22 /* CloseBracketToken */: case 20 /* CloseParenToken */: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - // if this token is the first token following the list of decorators, we do not need to indent - return indentation; - } - } - switch (kind) { - // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: - return indentation; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: { - if (container.kind === 252 /* JsxOpeningElement */ || - container.kind === 253 /* JsxClosingElement */ || - container.kind === 251 /* JsxSelfClosingElement */) { - return indentation; - } - break; - } - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: { - if (container.kind !== 173 /* MappedType */) { - return indentation; - } - break; - } - } - // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 17 /* OpenBraceToken */: + case 18 /* CloseBraceToken */: + case 19 /* OpenParenToken */: + case 20 /* CloseParenToken */: + case 82 /* ElseKeyword */: + case 106 /* WhileKeyword */: + case 57 /* AtToken */: + return false; + case 41 /* SlashToken */: + case 29 /* GreaterThanToken */: + switch (container.kind) { + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: + return false; + } + break; + case 21 /* OpenBracketToken */: + case 22 /* CloseBracketToken */: + if (container.kind !== 173 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; } @@ -89814,7 +92668,7 @@ var ts; // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes - // such tokens will be consumed in processChildNode for for the child that follows them + // such tokens will be consumed in processChildNode for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { @@ -90036,23 +92890,25 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0 /* None */; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAction = 2 /* LineRemoved */; - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); - } - } - else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAction = 1 /* LineAdded */; - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -90200,14 +93056,16 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1 /* Ignore */: // no action required - return; + return 0 /* None */; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } break; case 4 /* NewLine */: @@ -90215,25 +93073,27 @@ var ts; // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } - break; } + return 0 /* None */; } } var LineAction; @@ -90246,7 +93106,7 @@ var ts; * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword - tokenAtPosition, predicate) { + tokenAtPosition, predicate) { if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { @@ -90345,12 +93205,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -90360,20 +93220,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -90693,11 +93546,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1 /* Unknown */; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: @@ -90817,6 +93672,7 @@ var ts; case 176 /* ArrayBindingPattern */: case 175 /* ObjectBindingPattern */: case 252 /* JsxOpeningElement */: + case 255 /* JsxOpeningFragment */: case 251 /* JsxSelfClosingElement */: case 260 /* JsxExpression */: case 151 /* MethodSignature */: @@ -90862,6 +93718,8 @@ var ts; (!!child.namedBindings && child.namedBindings.kind !== 242 /* NamedImports */); case 250 /* JsxElement */: return childKind !== 253 /* JsxClosingElement */; + case 254 /* JsxFragment */: + return childKind !== 256 /* JsxClosingFragment */; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -91027,10 +93885,13 @@ var ts; this.formatContext = formatContext; this.validator = validator; this.changes = []; + this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + // Map from class id to nodes to insert at the start + this.nodesInsertedAtClassStarts = ts.createMap(); this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -91045,14 +93906,14 @@ var ts; if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, node, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: { pos: startPosition, end: endPosition } }); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { @@ -91069,6 +93930,9 @@ var ts; this.deleteNode(sourceFile, node); return this; } + var id = ts.getNodeId(node); + ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); + this.deletedNodesInLists[id] = true; if (index !== containingList.length - 1) { var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { @@ -91082,9 +93946,17 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); + var prev = containingList[index - 1]; + if (this.deletedNodesInLists[ts.getNodeId(prev)]) { + var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + var end = getAdjustedEndPosition(sourceFile, node, {}); + this.deleteRange(sourceFile, { pos: pos, end: end }); + } + else { + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); + if (previousToken && isSeparator(node, previousToken)) { + this.deleteNodeRange(sourceFile, previousToken, node); + } } } return this; @@ -91126,37 +93998,93 @@ var ts; }); return this; }; - ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); - }; - ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, oldNodes[0], options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, ts.lastOrUndefined(oldNodes), options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes) { + this.replaceWithMultiple(sourceFile, oldNode.getStart(sourceFile), oldNode.getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; - ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - return this.replaceWithMultiple(sourceFile, range.pos, range.end, newNodes, options); - }; - ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { - var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceWithMultiple(sourceFile, startPosition, endPosition, newNodes, options); + ChangeTracker.prototype.replaceNodesWithNodes = function (sourceFile, oldNodes, newNodes) { + this.replaceWithMultiple(sourceFile, ts.first(oldNodes).getStart(sourceFile), ts.last(oldNodes).getEnd(), newNodes, { nodeSeparator: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); return this; }; - ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start); - return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, options); + ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + var pos = getInsertionPositionAtSourceFileTop(sourceFile); + this.insertNodeAt(sourceFile, pos, newNode, { + prefix: pos === 0 ? undefined : this.newLineCharacter, + suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), + }); }; - ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) { - if (options === void 0) { options = {}; } - if ((ts.isStatementButNotDeclaration(after)) || + ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { + if (blankLineBetween === void 0) { blankLineBetween = false; } + var startPosition = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); + return this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + }; + ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { + var pos = before.getStart(sourceFile); + this.replaceWithSingle(sourceFile, pos, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.changeIdentifierToPropertyAccess = function (sourceFile, prefix, node) { + var startPosition = getAdjustedStartPosition(sourceFile, node, {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, ts.createPropertyAccess(ts.createIdentifier(prefix), ""), {}); + }; + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + if (ts.isStatement(before) || ts.isClassElement(before)) { + return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(before)) { + return { suffix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { + var firstStatement = ts.firstOrUndefined(ctr.body.statements); + if (!firstStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [newStatement].concat(ctr.body.statements)); + } + else { + this.insertNodeBefore(sourceFile, firstStatement, newStatement); + } + }; + ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { + var lastStatement = ts.lastOrUndefined(ctr.body.statements); + if (!lastStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, ctr.body.statements.concat([newStatement])); + } + else { + this.insertNodeAfter(sourceFile, lastStatement, newStatement); + } + }; + ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + }; + ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { + var startPosition = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + this.replaceWithSingle(sourceFile, startPosition, startPosition, newNode, { + prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, + suffix: this.newLineCharacter + }); + }; + ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + var firstMember = ts.firstOrUndefined(cls.members); + if (!firstMember) { + var id = ts.getNodeId(cls).toString(); + var newMembers = this.nodesInsertedAtClassStarts.get(id); + if (newMembers) { + ts.Debug.assert(newMembers.sourceFile === sourceFile && newMembers.cls === cls); + newMembers.members.push(newElement); + } + else { + this.nodesInsertedAtClassStarts.set(id, { sourceFile: sourceFile, cls: cls, members: [newElement] }); + } + } + else { + this.insertNodeBefore(sourceFile, firstMember, newElement); + } + }; + ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { + if (ts.isStatementButNotDeclaration(after) || after.kind === 150 /* PropertyDeclaration */ || after.kind === 149 /* PropertySignature */ || after.kind === 151 /* MethodSignature */) { @@ -91172,8 +94100,20 @@ var ts; }); } } - var endPosition = getAdjustedEndPosition(sourceFile, after, options); - return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, options); + var endPosition = getAdjustedEndPosition(sourceFile, after, {}); + return this.replaceWithSingle(sourceFile, endPosition, endPosition, newNode, this.getInsertNodeAfterOptions(after)); + }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { + if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + } + else if (ts.isStatement(node) || ts.isClassElement(node) || ts.isTypeElement(node)) { + return { suffix: this.newLineCharacter }; + } + else if (ts.isVariableDeclaration(node)) { + return { prefix: ", " }; + } + throw ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, @@ -91314,8 +94254,19 @@ var ts; } return this; }; + ChangeTracker.prototype.finishInsertNodeAtClassStart = function () { + var _this = this; + this.nodesInsertedAtClassStarts.forEach(function (_a) { + var sourceFile = _a.sourceFile, cls = _a.cls, members = _a.members; + var newCls = cls.kind === 230 /* ClassDeclaration */ + ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) + : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); + _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + }); + }; ChangeTracker.prototype.getChanges = function () { var _this = this; + this.finishInsertNodeAtClassStart(); var changesPerFile = ts.createMap(); // group changes per file for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { @@ -91495,6 +94446,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -91533,12 +94516,53 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; }()); + function getInsertionPositionAtSourceFileTop(_a) { + var text = _a.text; + var shebang = ts.getShebang(text); + var position = 0; + if (shebang !== undefined) { + position = shebang.length; + advancePastLineBreak(); + } + // For a source file, it is possible there are detached comments we should not skip + var ranges = ts.getLeadingCommentRanges(text, position); + if (!ranges) + return position; + // However we should still skip a pinned comment at the top + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + position = ranges[0].end; + advancePastLineBreak(); + ranges = ranges.slice(1); + } + // As well as any triple slash references + for (var _i = 0, ranges_1 = ranges; _i < ranges_1.length; _i++) { + var range = ranges_1[_i]; + if (range.kind === 2 /* SingleLineCommentTrivia */ && ts.isRecognizedTripleSlashComment(text, range.pos, range.end)) { + position = range.end; + advancePastLineBreak(); + continue; + } + break; + } + return position; + function advancePastLineBreak() { + if (position < text.length) { + var charCode = text.charCodeAt(position); + if (ts.isLineBreak(charCode)) { + position++; + if (position < text.length && charCode === 13 /* carriageReturn */ && text.charCodeAt(position) === 10 /* lineFeed */) { + position++; + } + } + } + } + } })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -91546,24 +94570,33 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var codeFixes = []; - function registerCodeFix(codeFix) { - ts.forEach(codeFix.errorCodes, function (error) { - var fixes = codeFixes[error]; - if (!fixes) { - fixes = []; - codeFixes[error] = fixes; - } - fixes.push(codeFix); - }); + var codeFixRegistrations = []; + var fixIdToRegistration = ts.createMap(); + function registerCodeFix(reg) { + for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { + var error = _a[_i]; + var registrations = codeFixRegistrations[error]; + if (!registrations) { + registrations = []; + codeFixRegistrations[error] = registrations; + } + registrations.push(reg); + } + if (reg.fixIds) { + for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { + var fixId = _c[_b]; + ts.Debug.assert(!fixIdToRegistration.has(fixId)); + fixIdToRegistration.set(fixId, reg); + } + } } codefix.registerCodeFix = registerCodeFix; function getSupportedErrorCodes() { - return Object.keys(codeFixes); + return Object.keys(codeFixRegistrations); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; function getFixes(context) { - var fixes = codeFixes[context.errorCode]; + var fixes = codeFixRegistrations[context.errorCode]; var allActions = []; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); @@ -91582,6 +94615,42 @@ var ts; return allActions; } codefix.getFixes = getFixes; + function getAllFixes(context) { + // Currently fixId is always a string. + return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString)).getAllCodeActions(context); + } + codefix.getAllFixes = getAllFixes; + function createCombinedCodeActions(changes, commands) { + return { changes: changes, commands: commands }; + } + function createFileTextChanges(fileName, textChanges) { + return { fileName: fileName, textChanges: textChanges }; + } + codefix.createFileTextChanges = createFileTextChanges; + function codeFixAll(context, errorCodes, use) { + var commands = []; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); + }); + return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); + } + codefix.codeFixAll = codeFixAll; + function codeFixAllWithTextChanges(context, errorCodes, use) { + var changes = []; + eachDiagnostic(context, errorCodes, function (diag) { return use(changes, diag); }); + changes.sort(function (a, b) { return b.span.start - a.span.start; }); + return createCombinedCodeActions([createFileTextChanges(context.sourceFile.fileName, changes)]); + } + codefix.codeFixAllWithTextChanges = codeFixAllWithTextChanges; + function eachDiagnostic(_a, errorCodes, cb) { + var program = _a.program, sourceFile = _a.sourceFile; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile); _i < _b.length; _i++) { + var diag = _b[_i]; + if (ts.contains(errorCodes, diag.code)) { + cb(diag); + } + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91592,14 +94661,15 @@ var ts; // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - return ts.flatMapIter(refactors.values(), function (refactor) { + return ts.arrayFrom(ts.flatMapIterator(refactors.values(), function (refactor) { return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? undefined : refactor.getAvailableActions(context); - }); + })); } refactor_1.getApplicableRefactors = getApplicableRefactors; function getEditsForRefactor(context, refactorName, actionName) { @@ -91618,22 +94688,24 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "addMissingInvocationForDecorator"; + var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var decorator = ts.getAncestor(token, 148 /* Decorator */); - ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); - var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, decorator.expression, replacement); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), - changes: changeTracker.getChanges() - }]; - } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var decorator = ts.findAncestor(token, ts.isDecorator); + ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); + var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); + changeTracker.replaceNode(sourceFile, decorator.expression, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91641,27 +94713,36 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "correctQualifiedNameToIndexedAccessType"; + var errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var qualifiedName = ts.getAncestor(token, 144 /* QualifiedName */); - ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); - if (!ts.isIdentifier(qualifiedName.left)) { + var qualifiedName = getQualifiedName(context.sourceFile, context.span.start); + if (!qualifiedName) return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); } - var leftText = qualifiedName.left.getText(sourceFile); - var rightText = qualifiedName.right.getText(sourceFile); - var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, qualifiedName, replacement); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), - changes: changeTracker.getChanges() - }]; - } + }); }, }); + function getQualifiedName(sourceFile, pos) { + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), ts.isQualifiedName); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; + } + function doChange(changeTracker, sourceFile, qualifiedName) { + var rightText = qualifiedName.right.text; + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -91669,55 +94750,61 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, + ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + var fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code], - getCodeActions: getActionForClassLikeIncorrectImplementsInterface + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var classDeclaration = getClass(sourceFile, span.start); + var checker = program.getTypeChecker(); + return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); + if (changes.length === 0) + return undefined; + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); + return { description: description, changes: changes, fixId: fixId }; + }); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenClassDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var classDeclaration = getClass(diag.file, diag.start); + if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { + for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + var implementedTypeNode = _a[_i]; + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + } + } + }); + }, }); - function getActionForClassLikeIncorrectImplementsInterface(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var classDeclaration = ts.getContainingClass(token); - if (!classDeclaration) { - return undefined; - } - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); + function getClass(sourceFile, pos) { + var classDeclaration = ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)); + ts.Debug.assert(!!classDeclaration); + return classDeclaration; + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var implementedType = checker.getTypeAtLocation(implementedTypeNode); + var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); + var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); var classType = checker.getTypeAtLocation(classDeclaration); - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(classDeclaration); - var hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, 1 /* Number */); - var hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, 0 /* String */); - var result = []; - for (var _i = 0, implementedTypeNodes_2 = implementedTypeNodes; _i < implementedTypeNodes_2.length; _i++) { - var implementedTypeNode = implementedTypeNodes_2[_i]; - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - var implementedType = checker.getTypeAtLocation(implementedTypeNode); - var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); - var newNodes = []; - createAndAddMissingIndexSignatureDeclaration(implementedType, 1 /* Number */, hasNumericIndexSignature, newNodes); - createAndAddMissingIndexSignatureDeclaration(implementedType, 0 /* String */, hasStringIndexSignature, newNodes); - newNodes = newNodes.concat(codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker)); - var message = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - if (newNodes.length > 0) { - pushAction(result, newNodes, message); - } + if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - return result; - function createAndAddMissingIndexSignatureDeclaration(type, kind, hasIndexSigOfKind, newNodes) { - if (hasIndexSigOfKind) { - return; - } + if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); + } + codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); - if (!indexInfoOfKind) { - return; + if (indexInfoOfKind) { + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); } - var newIndexSignatureDeclaration = checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration); - newNodes.push(newIndexSignatureDeclaration); - } - function pushAction(result, newNodes, description) { - result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -91727,157 +94814,175 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ]; + var fixId = "addMissingMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, - ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code], - getCodeActions: getActionsForAddMissingMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + var addMember = inJs ? + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var seenNames = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var program = context.program; + var info = getInfo(diag.file, diag.start, program.getTypeChecker()); + if (!info) + return; + var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + if (!ts.addToSeen(seenNames, token.text)) { + return; + } + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + } + else { + if (inJs) { + addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); + addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + } + } + }); + }, }); - function getActionsForAddMissingMember(context) { - var tokenSourceFile = context.sourceFile; - var start = context.span.start; + function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(tokenSourceFile, start, /*includeJsDocComment*/ false); - if (token.kind !== 71 /* Identifier */) { + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false); + if (!ts.isIdentifier(token)) { + return undefined; + } + var classAndMakeStatic = getClassAndMakeStatic(token, checker); + if (!classAndMakeStatic) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent)) { + var classDeclaration = classAndMakeStatic.classDeclaration, makeStatic = classAndMakeStatic.makeStatic; + var classDeclarationSourceFile = classDeclaration.getSourceFile(); + var inJs = ts.isInJavaScriptFile(classDeclarationSourceFile); + var call = ts.tryCast(token.parent.parent, ts.isCallExpression); + return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; + } + function getClassAndMakeStatic(token, checker) { + var parent = token.parent; + if (!ts.isPropertyAccessExpression(parent)) { return undefined; } - var tokenName = token.getText(tokenSourceFile); - var makeStatic = false; - var classDeclaration; - if (token.parent.expression.kind === 99 /* ThisKeyword */) { + if (parent.expression.kind === 99 /* ThisKeyword */) { var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); if (!ts.isClassElement(containingClassMemberDeclaration)) { return undefined; } - classDeclaration = containingClassMemberDeclaration.parent; + var classDeclaration = containingClassMemberDeclaration.parent; // Property accesses on `this` in a static method are accesses of a static member. - makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */); + return ts.isClassLike(classDeclaration) ? { classDeclaration: classDeclaration, makeStatic: ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */) } : undefined; } else { - var checker = context.program.getTypeChecker(); - var leftExpression = token.parent.expression; - var leftExpressionType = checker.getTypeAtLocation(leftExpression); - if (leftExpressionType.flags & 65536 /* Object */) { - var symbol = leftExpressionType.symbol; - if (symbol.flags & 32 /* Class */) { - classDeclaration = symbol.declarations && symbol.declarations[0]; - if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { - // The expression is a class symbol but the type is not the instance-side. - makeStatic = true; - } - } + var leftExpressionType = checker.getTypeAtLocation(parent.expression); + var symbol = leftExpressionType.symbol; + if (!(leftExpressionType.flags & 65536 /* Object */ && symbol.flags & 32 /* Class */)) { + return undefined; } + var classDeclaration = ts.cast(ts.first(symbol.declarations), ts.isClassLike); + // The expression is a class symbol but the type is not the instance-side. + return { classDeclaration: classDeclaration, makeStatic: leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol) }; } - if (!classDeclaration || !ts.isClassLike(classDeclaration)) { + } + function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); + if (changes.length === 0) return undefined; - } - var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); - var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); - return ts.isInJavaScriptFile(classDeclarationSourceFile) ? - getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : - getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); - function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ false); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - if (makeStatic) { - if (classDeclaration.kind === 200 /* ClassExpression */) { - return actions; - } - var className = classDeclaration.name.getText(); - var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); - var initializeStaticAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), - changes: staticInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeStaticAction); - return actions; - } - else { - var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); - if (!classConstructor) { - return actions; - } - var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyInitializationChangeTracker.insertNodeBefore(classDeclarationSourceFile, classConstructor.body.getLastToken(), propertyInitialization, { suffix: context.newLineCharacter }); - var initializeAction = { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), - changes: propertyInitializationChangeTracker.getChanges() - }; - (actions || (actions = [])).push(initializeAction); - return actions; - } - } - function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { - var actions; - var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ true); - if (methodCodeAction) { - actions = [methodCodeAction]; - } - var typeNode; - if (token.parent.parent.kind === 195 /* BinaryExpression */) { - var binaryExpression = token.parent.parent; - var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; - var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); - } - typeNode = typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); - var property = ts.createProperty( - /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, - /*questionToken*/ undefined, typeNode, - /*initializer*/ undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0; - actions = ts.append(actions, { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: propertyChangeTracker.getChanges() - }); - if (!makeStatic) { - // Index signatures cannot have the static modifier. - var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); - var indexingParameter = ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, "x", - /*questionToken*/ undefined, stringTypeNode, - /*initializer*/ undefined); - var indexSignature = ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); - actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), - changes: indexSignatureChangeTracker.getChanges() - }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); + return { description: description, changes: changes, fixId: fixId }; + } + function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { + if (makeStatic) { + if (classDeclaration.kind === 200 /* ClassExpression */) { + return; } - return actions; + var className = classDeclaration.name.getText(); + var staticInitialization = initializePropertyToUndefined(ts.createIdentifier(className), tokenName); + changeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization); } - function getActionForMethodDeclaration(includeTypeScriptSyntax) { - if (token.parent.parent.kind === 182 /* CallExpression */) { - var callExpression = token.parent.parent; - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); - methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); - var diag = makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0; - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag), [tokenName]), - changes: methodDeclarationChangeTracker.getChanges() - }; + else { + var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); + if (!classConstructor) { + return; } + var propertyInitialization = initializePropertyToUndefined(ts.createThis(), tokenName); + changeTracker.insertNodeAtConstructorEnd(classDeclarationSourceFile, classConstructor, propertyInitialization); + } + } + function initializePropertyToUndefined(obj, propertyName) { + return ts.createStatement(ts.createAssignment(ts.createPropertyAccess(obj, propertyName), ts.createIdentifier("undefined"))); + } + function getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic) { + var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); + var addProp = createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, token.text, typeNode); + return makeStatic ? [addProp] : [addProp, createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, token.text, typeNode)]; + } + function getTypeNode(checker, classDeclaration, token) { + var typeNode; + if (token.parent.parent.kind === 195 /* BinaryExpression */) { + var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } + return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + var property = ts.createProperty( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, + /*questionToken*/ undefined, typeNode, + /*initializer*/ undefined); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { + // Index signatures cannot have the static modifier. + var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); + var indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, "x", + /*questionToken*/ undefined, stringTypeNode, + /*initializer*/ undefined); + var indexSignature = ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [indexingParameter], typeNode); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); + // No fixId here because code-fix-all currently only works on adding individual named properties. + return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + } + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); + return { description: description, changes: changes, fixId: fixId }; + } + function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -91886,18 +94991,35 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], - getCodeActions: getActionsForCorrectSpelling + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.program.getTypeChecker()); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); + return [{ description: description, changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context.program.getTypeChecker()); + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion); + }); }, }); - function getActionsForCorrectSpelling(context) { - var sourceFile = context.sourceFile; + function getInfo(sourceFile, pos, checker) { // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 - var checker = context.program.getTypeChecker(); + var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852 var suggestion; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 71 /* Identifier */); @@ -91910,18 +95032,10 @@ var ts; ts.Debug.assert(name !== undefined, "name should be defined"); suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - if (suggestion) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: node.getStart(), length: node.getWidth() }, - newText: suggestion - }], - }], - }]; - } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); } function convertSemanticMeaningToSymbolFlags(meaning) { var flags = 0; @@ -91943,31 +95057,39 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixCannotFindModule"; + var errorCodes = [ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, - ], + errorCodes: errorCodes, 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, sourceFile.fileName, token.text); - return action && [action]; + var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); + return codeAction && [__assign({ fixId: fixId }, codeAction)]; }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { + var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + if (pkg) { + commands.push(getCommand(diag.file.fileName, pkg)); + } + }); }, }); - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + function getModuleName(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; + } + function getCommand(fileName, packageName) { + return { type: "install package", file: fileName, packageName: packageName }; + } + function getTypesPackageNameToInstall(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: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [typesPackageName]), + // If !registry, registry not available yet, can't do anything. + return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; + } + function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { + var packageName = getTypesPackageNameToInstall(host, moduleName); + return packageName === undefined ? undefined : { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), changes: [], - commands: [{ type: "install package", file: fileName, packageName: typesPackageName }], + commands: [getCommand(fileName, packageName)], }; } codefix.tryGetCodeActionForInstallPackageTypes = tryGetCodeActionForInstallPackageTypes; @@ -91978,44 +95100,45 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var errorCodes = [ + ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, + ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, + ]; + var fixId = "fixClassDoesntImplementInheritedAbstractMember"; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code], - getCodeActions: getActionForClassLikeMissingAbstractMember - }); - codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code], - getCodeActions: getActionForClassLikeMissingAbstractMember + errorCodes: errorCodes, + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + }); + return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + addMissingMembers(getClass(diag.file, diag.start), context.sourceFile, context.program.getTypeChecker(), changes); + }); }, }); - function getActionForClassLikeMissingAbstractMember(context) { - var sourceFile = context.sourceFile; - var start = context.span.start; + function getClass(sourceFile, pos) { // This is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - if (ts.isClassLike(token.parent)) { - var classDeclaration = token.parent; - var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); - var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); - // Note that this is ultimately derived from a map indexed by symbol names, - // so duplicates cannot occur. - var extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType); - var abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember); - var newNodes = codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker); - var changes = codefix.newNodesToChanges(newNodes, ts.getOpenBraceOfClassLike(classDeclaration, sourceFile), context); - if (changes && changes.length > 0) { - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), - changes: changes - }]; - } - } - return undefined; + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var classDeclaration = token.parent; + ts.Debug.assert(ts.isClassLike(classDeclaration)); + return classDeclaration; + } + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { + var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); + // Note that this is ultimately derived from a map indexed by symbol names, + // so duplicates cannot occur. + var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { - var decls = symbol.getDeclarations(); - ts.Debug.assert(!!(decls && decls.length > 0)); - var flags = ts.getModifierFlags(decls[0]); + // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files + // (now named `codeFixClassExtendAbstractPrivateProperty.ts`) + var flags = ts.getModifierFlags(ts.first(symbol.getDeclarations())); return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -92025,48 +95148,54 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "classSuperMustPrecedeThisAccess"; + var errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 99 /* ThisKeyword */) { - return undefined; - } - var constructor = ts.getContainingFunction(token); - var superCall = findSuperCall(constructor.body); - if (!superCall) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) return undefined; - } - // figure out if the `this` access is actually inside the supercall - // i.e. super(this.a), since in that case we won't suggest a fix - if (superCall.expression && superCall.expression.kind === 182 /* CallExpression */) { - var expressionArguments = superCall.expression.arguments; - for (var _i = 0, expressionArguments_1 = expressionArguments; _i < expressionArguments_1.length; _i++) { - var arg = expressionArguments_1[_i]; - if (arg.expression === token) { - return undefined; - } - } - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); - changeTracker.deleteNode(sourceFile, superCall); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), - changes: changeTracker.getChanges() - }]; - function findSuperCall(n) { - if (n.kind === 211 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { - return n; - } - if (ts.isFunctionLike(n)) { - return undefined; + var constructor = nodes.constructor, superCall = nodes.superCall; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var seenClasses = ts.createMap(); // Ensure we only do this once per class. + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + var constructor = nodes.constructor, superCall = nodes.superCall; + if (ts.addToSeen(seenClasses, ts.getNodeId(constructor.parent))) { + doChange(changes, sourceFile, constructor, superCall); } - return ts.forEachChild(n, findSuperCall); - } - } + }); + }, }); + function doChange(changes, sourceFile, constructor, superCall) { + changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); + changes.deleteNode(sourceFile, superCall); + } + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 99 /* ThisKeyword */); + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + // figure out if the `this` access is actually inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + return superCall && !superCall.expression.arguments.some(function (arg) { return ts.isPropertyAccessExpression(arg) && arg.expression === token; }) ? { constructor: constructor, superCall: superCall } : undefined; + } + function findSuperCall(n) { + return ts.isExpressionStatement(n) && ts.isSuperCall(n.expression) + ? n + : ts.isFunctionLike(n) + ? undefined + : ts.forEachChild(n, findSuperCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92074,23 +95203,30 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "constructorForDerivedNeedSuperCall"; + var errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 123 /* ConstructorKeyword */) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); - changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), - changes: changeTracker.getChanges() - }]; - } + var sourceFile = context.sourceFile, span = context.span; + var ctr = getNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); + return token.parent; + } + function doChange(changes, sourceFile, ctr) { + var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); + changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92098,40 +95234,51 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "extendsInterfaceBecomesImplements"; + var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var classDeclNode = ts.getContainingClass(token); - if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { + var nodes = getNodes(sourceFile, context.span.start); + if (!nodes) return undefined; + var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (nodes) + doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }); }, + }); + function getNodes(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var heritageClauses = ts.getContainingClass(token).heritageClauses; + var extendsToken = heritageClauses[0].getFirstToken(); + return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; + } + function doChanges(changes, sourceFile, extendsToken, heritageClauses) { + changes.replaceRange(sourceFile, { pos: extendsToken.getStart(), end: extendsToken.end }, ts.createToken(108 /* ImplementsKeyword */)); + // If there is already an implements clause, replace the implements keyword with a comma. + if (heritageClauses.length === 2 && + heritageClauses[0].token === 85 /* ExtendsKeyword */ && + heritageClauses[1].token === 108 /* ImplementsKeyword */) { + var implementsToken = heritageClauses[1].getFirstToken(); + var implementsFullStart = implementsToken.getFullStart(); + changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, ts.createToken(26 /* CommaToken */)); + // Rough heuristic: delete trailing whitespace after keyword so that it's not excessive. + // (Trailing because leading might be indentation, which is more sensitive.) + var text = sourceFile.text; + var end = implementsToken.end; + while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + end++; } - var heritageClauses = classDeclNode.heritageClauses; - if (!(heritageClauses && heritageClauses.length > 0)) { - return undefined; - } - var extendsToken = heritageClauses[0].getFirstToken(); - if (!(extendsToken && extendsToken.kind === 85 /* ExtendsKeyword */)) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); - // We replace existing keywords with commas. - for (var i = 1; i < heritageClauses.length; i++) { - var keywordToken = heritageClauses[i].getFirstToken(); - if (keywordToken) { - changeTracker.replaceNode(sourceFile, keywordToken, ts.createToken(26 /* CommaToken */)); - } - } - var result = [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), - changes: changeTracker.getChanges() - }]; - return result; + changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end: end }); } - }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92139,22 +95286,27 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "forgottenThisPropertyAccess"; + var errorCodes = [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - if (token.kind !== 71 /* Identifier */) { - return undefined; - } - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), - changes: changeTracker.getChanges() - }]; - } + var token = getNode(sourceFile, context.span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + }); }, }); + function getNode(sourceFile, pos) { + return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isIdentifier); + } + function doChange(changes, sourceFile, token) { + changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92162,183 +95314,311 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixIdPrefix = "unusedIdentifier_prefix"; + var fixIdDelete = "unusedIdentifier_delete"; + var errorCodes = [ + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, - ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ], + errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - // this handles var ["computed"] = 12; - if (token.kind === 21 /* OpenBracketToken */) { - token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); + var token = getToken(sourceFile, context.span.start); + var result = []; + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + if (deletion.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); + result.push({ description: description, changes: deletion, fixId: fixIdDelete }); } - switch (token.kind) { - case 71 /* Identifier */: - return deleteIdentifierOrPrefixWithUnderscore(token, context.errorCode); - case 150 /* PropertyDeclaration */: - case 241 /* NamespaceImport */: - return [deleteNode(token.parent)]; + var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, context.errorCode, sourceFile, token); }); + if (prefix.length) { + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); + result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + } + return result; + }, + fixIds: [fixIdPrefix, fixIdDelete], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var sourceFile = context.sourceFile; + var token = getToken(diag.file, diag.start); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: + tryDeleteDeclaration(changes, sourceFile, token); + break; default: - return deleteDefault(); + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); }, + }); + function getToken(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + // this handles var ["computed"] = 12; + return token.kind === 21 /* OpenBracketToken */ ? ts.getTokenAtPosition(sourceFile, pos + 1, /*includeJsDocComment*/ false) : token; + } + function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { + // Don't offer to prefix a property. + if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) { + changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + } + } + function canPrefix(token) { + switch (token.parent.kind) { + case 147 /* Parameter */: + return true; + case 227 /* VariableDeclaration */: { + var varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 217 /* ForOfStatement */: + case 216 /* ForInStatement */: + return true; + } } - function deleteDefault() { - if (ts.isDeclarationName(token)) { - return [deleteNode(token.parent)]; + } + return false; + } + function tryDeleteDeclaration(changes, sourceFile, token) { + switch (token.kind) { + case 71 /* Identifier */: + tryDeleteIdentifier(changes, sourceFile, token); + break; + case 150 /* PropertyDeclaration */: + case 241 /* NamespaceImport */: + changes.deleteNode(sourceFile, token.parent); + break; + default: + tryDeleteDefault(changes, sourceFile, token); + } + } + function tryDeleteDefault(changes, sourceFile, token) { + if (ts.isDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(token)) { + changes.deleteNode(sourceFile, token.parent.parent); + } + } + function tryDeleteIdentifier(changes, sourceFile, identifier) { + var parent = identifier.parent; + switch (parent.kind) { + case 227 /* VariableDeclaration */: + tryDeleteVariableDeclaration(changes, sourceFile, parent); + break; + case 146 /* TypeParameter */: + var typeParameters = parent.parent.typeParameters; + if (typeParameters.length === 1) { + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + changes.deleteNodeRange(sourceFile, previousToken, nextToken); } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return [deleteNode(token.parent.parent)]; + else { + changes.deleteNodeInList(sourceFile, parent); + } + break; + case 147 /* Parameter */: + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } else { - return undefined; + changes.deleteNodeInList(sourceFile, parent); } - } - function prefixIdentifierWithUnderscore(identifier) { - var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), - changes: [{ - fileName: sourceFile.path, - textChanges: [{ - span: { start: startPosition, length: 0 }, - newText: "_" - }] - }] - }; - } - function deleteIdentifierOrPrefixWithUnderscore(identifier, errorCode) { - var parent = identifier.parent; - switch (parent.kind) { - case 227 /* VariableDeclaration */: - return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); - case 146 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - return [deleteNodeRange(previousToken, nextToken)]; - } - else { - return [deleteNodeInList(parent)]; - } - case 147 /* Parameter */: - var functionDeclaration = parent.parent; - var deleteAction = functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent); - return errorCode === ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code - ? [deleteAction] - : [deleteAction, prefixIdentifierWithUnderscore(identifier)]; - // handle case where 'import a = A;' - case 238 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); - return [deleteNode(importEquals)]; - case 243 /* ImportSpecifier */: - var namedImports = parent.parent; - if (namedImports.elements.length === 1) { - return deleteNamedImportBinding(namedImports); - } - else { - // delete import specifier - return [deleteNodeInList(parent)]; - } - case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' - var importClause = parent; - if (!importClause.namedBindings) { - var importDecl = ts.getAncestor(importClause, 239 /* ImportDeclaration */); - return [deleteNode(importDecl)]; - } - else { - // import |d,| * as ns from './file' - var start_6 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; - } - else { - return [deleteNode(importClause.name)]; - } - } - case 241 /* NamespaceImport */: - return deleteNamedImportBinding(parent); - default: - return deleteDefault(); + break; + // handle case where 'import a = A;' + case 238 /* ImportEqualsDeclaration */: + var importEquals = ts.getAncestor(identifier, 238 /* ImportEqualsDeclaration */); + changes.deleteNode(sourceFile, importEquals); + break; + case 243 /* ImportSpecifier */: + var namedImports = parent.parent; + if (namedImports.elements.length === 1) { + tryDeleteNamedImportBinding(changes, sourceFile, namedImports); } - } - function deleteNamedImportBinding(namedBindings) { - if (namedBindings.parent.name) { - // Delete named imports while preserving the default import - // import d|, * as ns| from './file' - // import d|, { a }| from './file' - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; - } - return undefined; + else { + // delete import specifier + changes.deleteNodeInList(sourceFile, parent); + } + break; + case 240 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + var importClause = parent; + if (!importClause.namedBindings) { + changes.deleteNode(sourceFile, ts.getAncestor(importClause, 239 /* ImportDeclaration */)); } else { - // Delete the entire import declaration - // |import * as ns from './file'| - // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); - return [deleteNode(importDecl)]; + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + changes.deleteNode(sourceFile, importClause.name); + } } + break; + case 241 /* NamespaceImport */: + tryDeleteNamedImportBinding(changes, sourceFile, parent); + break; + default: + tryDeleteDefault(changes, sourceFile, identifier); + break; + } + } + function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) { + if (namedBindings.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); } - // token.parent is a variableDeclaration - function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { - switch (varDecl.parent.parent.kind) { - case 215 /* ForStatement */: - var forStatement = varDecl.parent.parent; - var forInitializer = forStatement.initializer; - return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; - case 217 /* ForOfStatement */: - var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); - var forOfInitializer = forOfStatement.initializer; - return [ - replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), - prefixIdentifierWithUnderscore(identifier) - ]; - case 216 /* ForInStatement */: - // There is no valid fix in the case of: - // for .. in - return [prefixIdentifierWithUnderscore(identifier)]; - default: - var variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - return [deleteNode(variableStatement)]; - } - else { - return [deleteNodeInList(varDecl)]; - } + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(namedBindings, 239 /* ImportDeclaration */); + changes.deleteNode(sourceFile, importDecl); + } + } + // token.parent is a variableDeclaration + function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { + switch (varDecl.parent.parent.kind) { + case 215 /* ForStatement */: { + var forStatement = varDecl.parent.parent; + var forInitializer = forStatement.initializer; + if (forInitializer.declarations.length === 1) { + changes.deleteNode(sourceFile, forInitializer); } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + break; } - function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); - } - function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); - } - function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); - } - function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); - } - function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); + case 217 /* ForOfStatement */: + var forOfStatement = varDecl.parent.parent; + ts.Debug.assert(forOfStatement.initializer.kind === 228 /* VariableDeclarationList */); + var forOfInitializer = forOfStatement.initializer; + changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); + break; + case 216 /* ForInStatement */: + case 225 /* TryStatement */: + break; + default: + var variableStatement = varDecl.parent.parent; + if (variableStatement.declarationList.declarations.length === 1) { + changes.deleteNode(sourceFile, variableStatement); + } + else { + changes.deleteNodeInList(sourceFile, varDecl); + } + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdPlain = "fixJSDocTypes_plain"; + var fixIdNullable = "fixJSDocTypes_nullable"; + var errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var checker = context.program.getTypeChecker(); + var info = getInfo(sourceFile, context.span.start, checker); + if (!info) + return undefined; + var typeNode = info.typeNode, type = info.type; + var original = typeNode.getText(sourceFile); + var actions = [fix(type, fixIdPlain)]; + if (typeNode.kind === 274 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); } - function makeChange(changeTracker) { + return actions; + function fix(type, fixId) { + var newText = typeString(type, checker); return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [createChange(typeNode, sourceFile, newText)])], + fixId: fixId, }; } + }, + fixIds: [fixIdPlain, fixIdNullable], + getAllCodeActions: function (context) { + var fixId = context.fixId, program = context.program, sourceFile = context.sourceFile; + var checker = program.getTypeChecker(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var info = getInfo(err.file, err.start, checker); + if (!info) + return; + var typeNode = info.typeNode, type = info.type; + var fixedType = typeNode.kind === 274 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + changes.push(createChange(typeNode, sourceFile, typeString(fixedType, checker))); + }); } }); + function getInfo(sourceFile, pos, checker) { + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); + var typeNode = decl && decl.type; + return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; + } + function createChange(declaration, sourceFile, newText) { + return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; + } + function typeString(type, checker) { + return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); + } + function isTypeContainer(node) { + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + switch (node.kind) { + case 203 /* AsExpression */: + case 156 /* CallSignature */: + case 157 /* ConstructSignature */: + case 229 /* FunctionDeclaration */: + case 154 /* GetAccessor */: + case 158 /* IndexSignature */: + case 173 /* MappedType */: + case 152 /* MethodDeclaration */: + case 151 /* MethodSignature */: + case 147 /* Parameter */: + case 150 /* PropertyDeclaration */: + case 149 /* PropertySignature */: + case 155 /* SetAccessor */: + case 232 /* TypeAliasDeclaration */: + case 185 /* TypeAssertionExpression */: + case 227 /* VariableDeclaration */: + return true; + default: + return false; + } + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92346,62 +95626,72 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "fixAwaitInSyncFunction"; + var errorCodes = [ + ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ]; codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], - getCodeActions: getActionsForJSDocTypes + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var nodes = getNodes(sourceFile, span.start); + if (!nodes) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); + return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var nodes = getNodes(diag.file, diag.start); + if (!nodes) + return; + doChange(changes, context.sourceFile, nodes); + }); }, }); - function getActionsForJSDocTypes(context) { - var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - // NOTE: Some locations are not handled yet: - // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments - var decl = ts.findAncestor(node, function (n) { - return n.kind === 203 /* AsExpression */ || - n.kind === 156 /* CallSignature */ || - n.kind === 157 /* ConstructSignature */ || - n.kind === 229 /* FunctionDeclaration */ || - n.kind === 154 /* GetAccessor */ || - n.kind === 158 /* IndexSignature */ || - n.kind === 173 /* MappedType */ || - n.kind === 152 /* MethodDeclaration */ || - n.kind === 151 /* MethodSignature */ || - n.kind === 147 /* Parameter */ || - n.kind === 150 /* PropertyDeclaration */ || - n.kind === 149 /* PropertySignature */ || - n.kind === 155 /* SetAccessor */ || - n.kind === 232 /* TypeAliasDeclaration */ || - n.kind === 185 /* TypeAssertionExpression */ || - n.kind === 227 /* VariableDeclaration */; - }); - if (!decl) - return; - var checker = context.program.getTypeChecker(); - var jsdocType = decl.type; - if (!jsdocType) - return; - var original = ts.getTextOfNode(jsdocType); - var type = checker.getTypeFromTypeNode(jsdocType); - var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; - if (jsdocType.kind === 274 /* JSDocNullableType */) { - // for nullable types, suggest the flow-compatible `T | null | undefined` - // in addition to the jsdoc/closure-compatible `T | null` - var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 4096 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); - actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); - } - return actions; - } - function createAction(declaration, fileName, original, replacement) { + function getReturnType(expr) { + if (expr.type) { + return expr.type; + } + if (ts.isVariableDeclaration(expr.parent) && + expr.parent.type && + ts.isFunctionTypeNode(expr.parent.type)) { + return expr.parent.type.type; + } + } + function getNodes(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var containingFunction = ts.getContainingFunction(token); + var insertBefore; + switch (containingFunction.kind) { + case 152 /* MethodDeclaration */: + insertBefore = containingFunction.name; + break; + case 229 /* FunctionDeclaration */: + case 187 /* FunctionExpression */: + insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); + break; + case 188 /* ArrowFunction */: + insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + break; + default: + return; + } return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), - changes: [{ - fileName: fileName, - textChanges: [{ - span: { start: declaration.getStart(), length: declaration.getWidth() }, - newText: replacement - }] - }], + insertBefore: insertBefore, + returnType: getReturnType(containingFunction) }; } + function doChange(changes, sourceFile, _a) { + var insertBefore = _a.insertBefore, returnType = _a.returnType; + if (returnType) { + var entityName = ts.getEntityNameFromTypeNode(returnType); + if (!entityName || entityName.kind !== 71 /* Identifier */ || entityName.text !== "Promise") { + changes.replaceNode(sourceFile, returnType, ts.createTypeReferenceNode("Promise", ts.createNodeArray([returnType]))); + } + } + changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, insertBefore); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -92417,7 +95707,10 @@ var ts; ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ], - getCodeActions: getImportCodeActions + getCodeActions: getImportCodeActions, + // TODO: GH#20315 + fixIds: [], + getAllCodeActions: ts.notImplemented, }); var ModuleSpecifierComparison; (function (ModuleSpecifierComparison) { @@ -92517,21 +95810,25 @@ var ts; return { description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)), changes: changes, + // TODO: GH#20315 + fixId: undefined, kind: kind, moduleSpecifier: moduleSpecifier }; } function convertToImportCodeFixContext(context) { var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var checker = context.program.getTypeChecker(); - var symbolToken = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); + var program = context.program; + var checker = program.getTypeChecker(); + // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. + var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, + program: program, checker: checker, - compilerOptions: context.program.getCompilerOptions(), + compilerOptions: program.getCompilerOptions(), cachedImportDeclarations: [], getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), symbolName: symbolToken.getText(), @@ -92568,7 +95865,10 @@ var ts; var declaration = declarations_13[_i]; var namespace = getNamespaceImportName(declaration); if (namespace) { - actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { + actions.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken)); + } } } } @@ -92613,7 +95913,7 @@ var ts; } } function getCodeActionForNewImport(context, moduleSpecifier) { - var kind = context.kind, sourceFile = context.sourceFile, newLineCharacter = context.newLineCharacter, symbolName = context.symbolName; + var kind = context.kind, sourceFile = context.sourceFile, symbolName = context.symbolName; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); @@ -92626,10 +95926,10 @@ var ts; /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); var changes = ChangeTracker.with(context, function (changeTracker) { if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: newLineCharacter }); + changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); } else { - changeTracker.insertNodeAt(sourceFile, ts.getSourceFileImportLocation(sourceFile), importDecl, { suffix: "" + newLineCharacter + newLineCharacter }); + changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); } }); // if this file doesn't have any import statements, insert an import statement and then insert a new line @@ -92643,6 +95943,12 @@ var ts; literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); return literal; } + function usesJsExtensionOnImports(sourceFile) { + return ts.firstDefined(sourceFile.imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -92656,68 +95962,86 @@ var ts; ts.Debug.assertNever(kind); } } - function getModuleSpecifiersForNewImport(sourceFile, moduleSymbols, options, getCanonicalFileName, host) { + function getModuleSpecifiersForNewImport(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; - var choicesForEachExportingModule = ts.mapIterator(ts.arrayIterator(moduleSymbols), function (moduleSymbol) { - var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options); - if (!baseUrl) { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; + var addJsExtension = usesJsExtensionOnImports(sourceFile); + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (moduleSymbol) { + return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { + var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); + var global = tryGetModuleNameFromAmbientModule(moduleSymbol) + || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + if (global) { + return [global]; + } + var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); + if (!baseUrl) { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; } - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + }); }); // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) - return ts.best(choicesForEachExportingModule, function (a, b) { return a[0].length < b[0].length; }); + return ts.best(ts.arrayIterator(choicesForEachExportingModule), function (a, b) { return a[0].length < b[0].length; }); } codefix.getModuleSpecifiersForNewImport = getModuleSpecifiersForNewImport; + /** + * Looks for a existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(program, _a) { + var fileName = _a.fileName; + var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === fileName ? res.originalPath : undefined; + }); + }); + return symlinks.length === 0 ? [fileName] : symlinks; + } function getRelativePathNParents(relativePath) { var count = 0; for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { @@ -92731,10 +96055,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -92742,14 +96067,14 @@ var ts; 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); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -92764,12 +96089,12 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName) { + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + return 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), options); + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); } }); } @@ -92877,15 +96202,25 @@ var ts; 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); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } - function removeExtensionAndIndexPostFix(fileName, options) { + function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); - return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs ? ts.removeSuffix(noExtension, "/index") : noExtension; + return addJsExtension + ? noExtension + ".js" + : ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -92905,7 +96240,7 @@ var ts; return [fromExistingImport]; } var existingDeclaration = ts.firstDefined(declarations, moduleSpecifierFromAnyImport); - var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); + var moduleSpecifiers = existingDeclaration ? [existingDeclaration] : getModuleSpecifiersForNewImport(ctx.program, ctx.sourceFile, moduleSymbols, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); return moduleSpecifiers.map(function (spec) { return getCodeActionForNewImport(ctx, spec); }); } function moduleSpecifierFromAnyImport(node) { @@ -92960,10 +96295,11 @@ var ts; * 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); + // Prefix the node instead of it replacing it, because this may be used for import completions and we don't want the text changes to overlap with the identifier being completed. + var changes = ChangeTracker.with(context, function (tracker) { + return tracker.changeIdentifierToPropertyAccess(sourceFile, namespacePrefix, symbolToken); + }); + return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes, "CodeChange", /*moduleSpecifier*/ undefined); } function getImportCodeActions(context) { var importFixContext = convertToImportCodeFixContext(context); @@ -92982,7 +96318,7 @@ var ts; } 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 */)); + symbol = checker.getAliasedSymbol(checker.resolveName(checker.getJsxNamespace(), symbolToken.parent.tagName, 107455 /* Value */, /*excludeGlobals*/ false)); symbolName = symbol.name; } else { @@ -93021,11 +96357,12 @@ var ts; forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { // check if this symbol is already used var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); @@ -93037,6 +96374,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -93103,6 +96455,7 @@ var ts; // Need `|| "_"` to ensure result isn't empty. return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -93110,16 +96463,44 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "disableJsDiagnostics"; + var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { + var diag = ts.Diagnostics[key]; + return diag.category === ts.DiagnosticCategory.Error ? diag.code : undefined; + }); codefix.registerCodeFix({ - errorCodes: getApplicableDiagnosticCodes(), - getCodeActions: getDisableJsDiagnosticsCodeActions + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + return undefined; + } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], + fixId: fixId, + }, + { + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), + changes: [codefix.createFileTextChanges(sourceFile.fileName, [{ + span: { + start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, + length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 + }, + newText: "// @ts-nocheck" + newLineCharacter + }])], + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + fixId: undefined, + }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + if (err.start !== undefined) { + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); + } + }); }, }); - function getApplicableDiagnosticCodes() { - var allDiagnostcs = ts.Diagnostics; - return Object.keys(allDiagnostcs) - .filter(function (d) { return allDiagnostcs[d] && allDiagnostcs[d].category === ts.DiagnosticCategory.Error; }) - .map(function (d) { return allDiagnostcs[d].code; }); - } function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) { var line = ts.getLineAndCharacterOfPosition(sourceFile, position).line; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); @@ -93144,32 +96525,6 @@ var ts; newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter }; } - function getDisableJsDiagnosticsCodeActions(context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { - return undefined; - } - return [{ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)] - }] - }, - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { - start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, - length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 - }, - newText: "// @ts-nocheck" + newLineCharacter - }] - }] - }]; - } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -93177,64 +96532,33 @@ var ts; (function (ts) { var codefix; (function (codefix) { - function newNodesToChanges(newNodes, insertAfter, context) { - var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); - for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { - var newNode = newNodes_1[_i]; - changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); - } - var changes = changeTracker.getChanges(); - if (!ts.some(changes)) { - return changes; - } - ts.Debug.assert(changes.length === 1); - var consolidatedChanges = [{ - fileName: changes[0].fileName, - textChanges: [{ - span: changes[0].textChanges[0].span, - newText: changes[0].textChanges.reduce(function (prev, cur) { return prev + cur.newText; }, "") - }] - }]; - return consolidatedChanges; - } - codefix.newNodesToChanges = newNodesToChanges; /** * Finds members of the resolved type that are missing in the class pointed to by class decl * and generates source code for the missing members. * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, out) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); - var newNodes = []; - for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { - var symbol = missingMembers_1[_i]; - var newNode = createNewNodeForMemberSymbol(symbol, classDeclaration, checker); - if (newNode) { - if (Array.isArray(newNode)) { - newNodes = newNodes.concat(newNode); - } - else { - newNodes.push(newNode); - } + for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { + var symbol = possiblyMissingSymbols_1[_i]; + if (!classMembers.has(symbol.escapedName)) { + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); } } - return newNodes; } codefix.createMissingMemberNodes = createMissingMemberNodes; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function createNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -93245,10 +96569,10 @@ var ts; case 149 /* PropertySignature */: case 150 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); - var property = ts.createProperty( + out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, - /*initializer*/ undefined); - return property; + /*initializer*/ undefined)); + break; case 151 /* MethodSignature */: case 152 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff @@ -93260,70 +96584,65 @@ var ts; // correspondence of declarations and signatures. var signatures = checker.getSignaturesOfType(type, 0 /* Call */); if (!ts.some(signatures)) { - return undefined; + break; } if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody()); + break; } - var signatureDeclarations = []; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var signature = signatures_8[_i]; - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + // Need to ensure nodes are fresh each time so they can have different positions. + outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody()); - if (methodDeclaration) { - signatureDeclarations.push(methodDeclaration); - } + outputMethod(signature, modifiers, name, createStubbedMethodBody()); } else { ts.Debug.assert(declarations.length === signatures.length); - var methodImplementingSignatures = createMethodImplementingSignatures(signatures, name, optional, modifiers); - signatureDeclarations.push(methodImplementingSignatures); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); } - return signatureDeclarations; - default: - return undefined; + break; } - function signatureToMethodDeclaration(signature, enclosingDeclaration, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); - if (signatureDeclaration) { - signatureDeclaration.decorators = undefined; - signatureDeclaration.modifiers = modifiers; - signatureDeclaration.name = name; - signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; - signatureDeclaration.body = body; - } - return signatureDeclaration; + function outputMethod(signature, modifiers, name, body) { + var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + if (method) + out(method); } } - function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { - var parameters = createDummyParameters(callExpression.arguments.length, /*names*/ undefined, /*minArgumentCount*/ undefined, includeTypeScriptSyntax); - var typeParameters; - if (includeTypeScriptSyntax) { - var typeArgCount = ts.length(callExpression.typeArguments); - for (var i = 0; i < typeArgCount; i++) { - var name = typeArgCount < 8 ? String.fromCharCode(84 /* T */ + i) : "T" + i; - var typeParameter = ts.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined); - (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); - } + function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + if (!signatureDeclaration) { + return undefined; } - var newMethod = ts.createMethod( + signatureDeclaration.decorators = undefined; + signatureDeclaration.modifiers = modifiers; + signatureDeclaration.name = name; + signatureDeclaration.questionToken = optional ? ts.createToken(55 /* QuestionToken */) : undefined; + signatureDeclaration.body = body; + return signatureDeclaration; + } + function getSynthesizedDeepClones(nodes) { + return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); + } + function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { + var typeArguments = _a.typeArguments, args = _a.arguments; + return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, /*asteriskToken*/ undefined, methodName, - /*questionToken*/ undefined, typeParameters, parameters, - /*type*/ includeTypeScriptSyntax ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, createStubbedMethodBody()); - return newMethod; + /*questionToken*/ undefined, + /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { + return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + }), + /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; - function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + function createDummyParameters(argCount, names, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { var newParameter = ts.createParameter( @@ -93332,7 +96651,7 @@ var ts; /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ addAnyType ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } @@ -93358,7 +96677,7 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -93377,7 +96696,6 @@ var ts; /*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); } - codefix.createStubbedMethod = createStubbedMethod; function createStubbedMethodBody() { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], @@ -93399,229 +96717,239 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + ]; codefix.registerCodeFix({ - errorCodes: [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - ], - getCodeActions: getActionsForAddExplicitTypeAnnotation + errorCodes: errorCodes, + getCodeActions: function (_a) { + var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; + if (ts.isSourceFileJavaScript(sourceFile)) { + return undefined; // TODO: GH#20113 + } + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var fix = getFix(sourceFile, token, errorCode, program, cancellationToken); + if (!fix) + return undefined; + var declaration = fix.declaration, textChanges = fix.textChanges; + var name = ts.getNameOfDeclaration(declaration); + var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name.getText()]); + return [{ description: description, changes: [{ fileName: sourceFile.fileName, textChanges: textChanges }], fixId: fixId }]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var seenFunctions = ts.createMap(); + return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { + var fix = getFix(sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + if (fix) + changes.push.apply(changes, fix.textChanges); + }); + }, }); - function getActionsForAddExplicitTypeAnnotation(_a) { - var sourceFile = _a.sourceFile, program = _a.program, start = _a.span.start, errorCode = _a.errorCode, cancellationToken = _a.cancellationToken; - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); - var writer; - if (ts.isInJavaScriptFile(token)) { - return undefined; - } - switch (token.kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 131 /* ReadonlyKeyword */: - // Allowed - break; + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; default: - return undefined; + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + function getFix(sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { + if (!isAllowedTokenKind(token.kind)) { + return undefined; } - var containingFunction = ts.getContainingFunction(token); - var checker = program.getTypeChecker(); switch (errorCode) { // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - return getCodeActionForVariableDeclaration(token.parent); - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: - return getCodeActionForVariableUsage(token); + return getCodeActionForVariableDeclaration(token.parent, sourceFile, program, cancellationToken); + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration, sourceFile, program, cancellationToken); + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessor(containingFunction)) { - return getCodeActionForSetAccessor(containingFunction); + return getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken); } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - return getCodeActionForParameters(token.parent); + return !seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction)) + ? getCodeActionForParameters(token.parent, containingFunction, sourceFile, program, cancellationToken) + : undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction) : undefined; + return ts.isGetAccessor(containingFunction) ? getCodeActionForGetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction) : undefined; - } - return undefined; - function getCodeActionForVariableDeclaration(declaration) { - if (!ts.isIdentifier(declaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(declaration.name); - var typeString = type && typeToString(type, declaration); - if (!typeString) { - return undefined; - } - return createCodeActions(declaration.name.getText(), declaration.name.getEnd(), ": " + typeString); - } - function getCodeActionForVariableUsage(token) { - var symbol = checker.getSymbolAtLocation(token); - return symbol && symbol.valueDeclaration && getCodeActionForVariableDeclaration(symbol.valueDeclaration); - } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 229 /* FunctionDeclaration */: - case 152 /* MethodDeclaration */: - case 153 /* Constructor */: - return true; - case 187 /* FunctionExpression */: - return !!declaration.name; - } - return false; + return ts.isSetAccessor(containingFunction) ? getCodeActionForSetAccessor(containingFunction, sourceFile, program, cancellationToken) : undefined; + default: + throw ts.Debug.fail(String(errorCode)); } - function getCodeActionForParameters(parameterDeclaration) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { - return undefined; - } - var types = inferTypeForParametersFromUsage(containingFunction) || - ts.map(containingFunction.parameters, function (p) { return ts.isIdentifier(p.name) && inferTypeForVariableFromUsage(p.name); }); - if (!types) { - return undefined; - } - var textChanges = ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (type && !parameter.type && !parameter.initializer) { - var typeString = typeToString(type, containingFunction); - return typeString ? { - span: { start: parameter.end, length: 0 }, - newText: ": " + typeString - } : undefined; - } - }).filter(function (c) { return !!c; }); - return textChanges.length ? [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_parameter_types_from_usage), [parameterDeclaration.name.getText()]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: textChanges - }] - }] : undefined; - } - function getCodeActionForSetAccessor(setAccessorDeclaration) { - var setAccessorParameter = setAccessorDeclaration.parameters[0]; - if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name) || - inferTypeForVariableFromUsage(setAccessorParameter.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - return createCodeActions(setAccessorDeclaration.name.getText(), setAccessorParameter.name.getEnd(), ": " + typeString); + } + function isAllowedTokenKind(kind) { + switch (kind) { + case 71 /* Identifier */: + case 24 /* DotDotDotToken */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + return true; + default: + return false; } - function getCodeActionForGetAccessor(getAccessorDeclaration) { - if (!ts.isIdentifier(getAccessorDeclaration.name)) { - return undefined; - } - var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name); - var typeString = type && typeToString(type, containingFunction); - if (!typeString) { - return undefined; - } - var closeParenToken = getFirstChildOfKind(getAccessorDeclaration, sourceFile, 20 /* CloseParenToken */); - return createCodeActions(getAccessorDeclaration.name.getText(), closeParenToken.getEnd(), ": " + typeString); + } + function getCodeActionForVariableDeclaration(declaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(declaration.name)) + return undefined; + var type = inferTypeForVariableFromUsage(declaration.name, sourceFile, program, cancellationToken); + return makeFix(declaration, declaration.name.getEnd(), type, program); + } + function isApplicableFunctionForInference(declaration) { + switch (declaration.kind) { + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + case 153 /* Constructor */: + return true; + case 187 /* FunctionExpression */: + return !!declaration.name; } - function createCodeActions(name, start, typeString) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Infer_type_of_0_from_usage), [name]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: start, length: 0 }, - newText: typeString - }] - }] - }]; + return false; + } + function getCodeActionForParameters(parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + return undefined; } - function getReferences(token) { - var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), token.getSourceFile(), token.getStart()); - ts.Debug.assert(!!references, "Found no references!"); - ts.Debug.assert(references.length === 1, "Found more references than expected"); - return ts.map(references[0].references, function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, sourceFile, program, cancellationToken) : undefined; }); + if (!types) + return undefined; + // We didn't actually find a set of type inference positions matching each parameter position + if (containingFunction.parameters.length !== types.length) { + return undefined; } - function inferTypeForVariableFromUsage(token) { - return InferFromReference.inferTypeFromReferences(getReferences(token), checker, cancellationToken); + var textChanges = ts.arrayFrom(ts.mapDefinedIterator(ts.zipToIterator(containingFunction.parameters, types), function (_a) { + var parameter = _a[0], type = _a[1]; + return type && !parameter.type && !parameter.initializer ? makeChange(containingFunction, parameter.end, type, program) : undefined; + })); + return textChanges.length ? { declaration: parameterDeclaration, textChanges: textChanges } : undefined; + } + function getCodeActionForSetAccessor(setAccessorDeclaration, sourceFile, program, cancellationToken) { + var setAccessorParameter = setAccessorDeclaration.parameters[0]; + if (!setAccessorParameter || !ts.isIdentifier(setAccessorDeclaration.name) || !ts.isIdentifier(setAccessorParameter.name)) { + return undefined; } - function inferTypeForParametersFromUsage(containingFunction) { - switch (containingFunction.kind) { - case 153 /* Constructor */: - case 187 /* FunctionExpression */: - case 229 /* FunctionDeclaration */: - case 152 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 153 /* Constructor */; - var searchToken = isConstructor ? - getFirstChildOfKind(containingFunction, sourceFile, 123 /* ConstructorKeyword */) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken), containingFunction, checker, cancellationToken); - } - } - } - function getTypeAccessiblityWriter() { - if (!writer) { - var str_1 = ""; - var typeIsAccessible_1 = true; - var writeText = function (text) { return str_1 += text; }; - writer = { - string: function () { return typeIsAccessible_1 ? str_1 : undefined; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { str_1 = ""; typeIsAccessible_1 = true; }, - trackSymbol: function (symbol, declaration, meaning) { - if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { - typeIsAccessible_1 = false; - } - }, - reportInaccessibleThisError: function () { typeIsAccessible_1 = false; }, - reportPrivateInBaseOfClassExpression: function () { typeIsAccessible_1 = false; }, - reportInaccessibleUniqueSymbolError: function () { typeIsAccessible_1 = false; } - }; - } - writer.clear(); - return writer; + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, sourceFile, program, cancellationToken) || + inferTypeForVariableFromUsage(setAccessorParameter.name, sourceFile, program, cancellationToken); + return makeFix(setAccessorParameter, setAccessorParameter.name.getEnd(), type, program); + } + function getCodeActionForGetAccessor(getAccessorDeclaration, sourceFile, program, cancellationToken) { + if (!ts.isIdentifier(getAccessorDeclaration.name)) { + return undefined; } - function typeToString(type, enclosingDeclaration) { - var writer = getTypeAccessiblityWriter(); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + var type = inferTypeForVariableFromUsage(getAccessorDeclaration.name, sourceFile, program, cancellationToken); + var closeParenToken = ts.findChildOfKind(getAccessorDeclaration, 20 /* CloseParenToken */, sourceFile); + return makeFix(getAccessorDeclaration, closeParenToken.getEnd(), type, program); + } + function makeFix(declaration, start, type, program) { + return type && { declaration: declaration, textChanges: [makeChange(declaration, start, type, program)] }; + } + function makeChange(declaration, start, type, program) { + var typeString = type && typeToString(type, declaration, program.getTypeChecker()); + return typeString === undefined ? undefined : { span: ts.createTextSpan(start, 0), newText: ": " + typeString }; + } + function getReferences(token, sourceFile, program, cancellationToken) { + var references = ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), sourceFile, token.getStart(sourceFile)); + if (!references || references.length !== 1) { + return []; } - function getFirstChildOfKind(node, sourcefile, kind) { - for (var _i = 0, _a = node.getChildren(sourcefile); _i < _a.length; _i++) { - var child = _a[_i]; - if (child.kind === kind) - return child; - } - return undefined; + return references[0].references.map(function (r) { return ts.getTokenAtPosition(program.getSourceFile(r.fileName), r.textSpan.start, /*includeJsDocComment*/ false); }); + } + function inferTypeForVariableFromUsage(token, sourceFile, program, cancellationToken) { + return InferFromReference.inferTypeFromReferences(getReferences(token, sourceFile, program, cancellationToken), program.getTypeChecker(), cancellationToken); + } + function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { + switch (containingFunction.kind) { + case 153 /* Constructor */: + case 187 /* FunctionExpression */: + case 229 /* FunctionDeclaration */: + case 152 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 153 /* Constructor */; + var searchToken = isConstructor ? + ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : + containingFunction.name; + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, sourceFile, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); + } } } + function getTypeAccessiblityWriter(checker) { + var str = ""; + var typeIsAccessible = true; + var writeText = function (text) { return str += text; }; + return { + getText: function () { return typeIsAccessible ? str : undefined; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + writeLine: function () { return writeText(" "); }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { str = ""; typeIsAccessible = true; }, + trackSymbol: function (symbol, declaration, meaning) { + if (checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility !== 0 /* Accessible */) { + typeIsAccessible = false; + } + }, + reportInaccessibleThisError: function () { typeIsAccessible = false; }, + reportPrivateInBaseOfClassExpression: function () { typeIsAccessible = false; }, + reportInaccessibleUniqueSymbolError: function () { typeIsAccessible = false; } + }; + } + function typeToString(type, enclosingDeclaration, checker) { + var writer = getTypeAccessiblityWriter(checker); + checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); + return writer.getText(); + } var InferFromReference; (function (InferFromReference) { function inferTypeFromReferences(references, checker, cancellationToken) { @@ -93635,6 +96963,9 @@ var ts; } InferFromReference.inferTypeFromReferences = inferTypeFromReferences; function inferTypeForParametersFromReferences(references, declaration, checker, cancellationToken) { + if (references.length === 0) { + return undefined; + } if (declaration.parameters) { var usageContext = {}; for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { @@ -93661,7 +96992,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); paramTypes[parameterIndex] = isRestParameter_1 ? checker.createArrayType(type) : type; } } @@ -93873,12 +97204,12 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), /*subtypeReduction*/ true)); + return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - return checker.createPromiseType(types.length ? checker.getUnionType(types, /*subtypeReduction*/ true) : checker.getAnyType()); + return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); @@ -93936,7 +97267,7 @@ var ts; } } if (types.length) { - var type = checker.getWidenedType(checker.getUnionType(types, /*subtypeReduction*/ true)); + var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); return isRestParameter ? checker.createArrayType(type) : type; } return undefined; @@ -93962,6 +97293,94 @@ var ts; })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + // This is the whole import statement, eg: + // import * as Bluebird from 'bluebird'; + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; + if (!ts.isImportDeclaration(node)) { + // No import quick fix for import calls + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + var replacement = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + var replacement_1 = ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 /* CallExpression */ : 183 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// /// /// @@ -93975,10 +97394,12 @@ var ts; /// /// /// +/// /// /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -93986,14 +97407,10 @@ var ts; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -94001,11 +97418,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -94215,15 +97632,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -94238,11 +97651,11 @@ var ts; if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -94257,7 +97670,6 @@ var ts; } var sourceFile = context.file; var ctorSymbol = getConstructorSymbol(context); - var newLine = context.formatContext.options.newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { @@ -94288,7 +97700,7 @@ var ts; return undefined; } // Because the preceding node could be touched, we need to insert nodes before delete nodes. - changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); + changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { var deleteCallback = deletes_1[_i]; deleteCallback(); @@ -94453,6 +97865,488 @@ var ts; })(convertFunctionToES6Class = refactor.convertFunctionToES6Class || (refactor.convertFunctionToES6Class = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var actionName = "Convert to ES6 module"; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { + return undefined; + } + var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); + return !isAtTriggerLocation(file, node) ? undefined : [ + { + name: actionName, + description: description, + actions: [ + { + description: description, + name: actionName, + }, + ], + }, + ]; + } + function isAtTriggerLocation(sourceFile, node, onSecondTry) { + if (onSecondTry === void 0) { onSecondTry = false; } + switch (node.kind) { + case 182 /* CallExpression */: + return isAtTopLevelRequire(node); + case 180 /* PropertyAccessExpression */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression); + case 228 /* VariableDeclarationList */: + var decl = node.declarations[0]; + return ts.isExportsOrModuleExportsOrAlias(sourceFile, decl.initializer); + case 227 /* VariableDeclaration */: + return ts.isExportsOrModuleExportsOrAlias(sourceFile, node.initializer); + default: + return ts.isExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node) + || !onSecondTry && isAtTriggerLocation(sourceFile, node.parent, /*onSecondTry*/ true); + } + } + function isAtTopLevelRequire(call) { + if (!ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + var propAccess = call.parent; + var varDecl = ts.isPropertyAccessExpression(propAccess) ? propAccess.parent : propAccess; + if (ts.isExpressionStatement(varDecl) && ts.isSourceFile(varDecl.parent)) { + return true; + } + if (!ts.isVariableDeclaration(varDecl)) { + return false; + } + var varDeclList = varDecl.parent; + if (varDeclList.kind !== 228 /* VariableDeclarationList */) { + return false; + } + var varStatement = varDeclList.parent; + return varStatement.kind === 209 /* VariableStatement */ && varStatement.parent.kind === 269 /* SourceFile */; + } + function getEditsForAction(context, _actionName) { + ts.Debug.assertEqual(actionName, _actionName); + var file = context.file, program = context.program; + ts.Debug.assert(ts.isSourceFileJavaScript(file)); + var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { + var moduleExportsChangedToDefault = convertFileToEs6Module(file, program.getTypeChecker(), changes, program.getCompilerOptions().target); + if (moduleExportsChangedToDefault) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var importingFile = _a[_i]; + fixImportOfModuleExports(importingFile, file, changes); + } + } + }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + function fixImportOfModuleExports(importingFile, exportingFile, changes) { + for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { + var moduleSpecifier = _a[_i]; + var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); + if (!imported || imported.resolvedFileName !== exportingFile.fileName) { + continue; + } + var parent = moduleSpecifier.parent; + switch (parent.kind) { + case 249 /* ExternalModuleReference */: { + var importEq = parent.parent; + changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + break; + } + case 182 /* CallExpression */: { + var call = parent; + if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { + changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + } + break; + } + } + } + } + /** @returns Whether we converted a `module.exports =` to a default export. */ + function convertFileToEs6Module(sourceFile, checker, changes, target) { + var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; + var exports = collectExportRenames(sourceFile, checker, identifiers); + convertExportsAccesses(sourceFile, exports, changes); + var moduleExportsChangedToDefault = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; + } + return moduleExportsChangedToDefault; + } + function collectExportRenames(sourceFile, checker, identifiers) { + var res = ts.createMap(); + forEachExportReference(sourceFile, function (node) { + var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; + if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) + || checker.resolveName(node.name.text, node, 107455 /* Value */, /*excludeGlobals*/ true))) { + // Unconditionally add an underscore in case `text` is a keyword. + res.set(text, makeUniqueName("_" + text, identifiers)); + } + }); + return res; + } + function convertExportsAccesses(sourceFile, exports, changes) { + forEachExportReference(sourceFile, function (node, isAssignmentLhs) { + if (isAssignmentLhs) { + return; + } + var text = node.name.text; + changes.replaceNode(sourceFile, node, ts.createIdentifier(exports.get(text) || text)); + }); + } + function forEachExportReference(sourceFile, cb) { + sourceFile.forEachChild(function recur(node) { + if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) { + var parent = node.parent; + cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */); + } + node.forEachChild(recur); + }); + } + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + switch (statement.kind) { + case 209 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + return false; + case 211 /* ExpressionStatement */: { + var expression = statement.expression; + switch (expression.kind) { + case 182 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + // For side-effecting require() call, just make a side-effecting import. + changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + } + return false; + } + case 195 /* BinaryExpression */: { + var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + } + } + } + // falls through + default: + return false; + } + } + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + var declarationList = statement.declarationList; + var foundImport = false; + var newNodes = ts.flatMap(declarationList.declarations, function (decl) { + var name = decl.name, initializer = decl.initializer; + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); + } + else { + // Move it out to its own variable statement. + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + } + }); + if (foundImport) { + // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + } + /** Converts `const name = require("moduleSpecifier").propertyName` */ + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: + case 176 /* ArrayBindingPattern */: { + // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` + var tmp = makeUniqueName(propertyName, identifiers); + return [ + makeSingleImport(tmp, propertyName, moduleSpecifier), + makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + // `const a = require("b").c` --> `import { c as a } from "./b"; + return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + default: + ts.Debug.assertNever(name); + } + } + function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + if (!ts.isPropertyAccessExpression(left)) { + return false; + } + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { + // `const alias = module.exports;` or `module.exports = alias;` can be removed. + changes.deleteNode(sourceFile, statement); + } + else { + var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; + var changedToDefaultExport = false; + if (!newNodes) { + (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + } + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + return changedToDefaultExport; + } + } + else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { + convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + } + return false; + var _a; + } + /** + * Convert `module.exports = { ... }` to individual exports.. + * We can't always do this if the module has interesting members -- then it will be a default export instead. + */ + function tryChangeModuleExportsObject(object) { + return ts.mapAllOrFail(object.properties, function (prop) { + switch (prop.kind) { + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + case 266 /* ShorthandPropertyAssignment */: + case 267 /* SpreadAssignment */: + return undefined; + case 265 /* PropertyAssignment */: { + var _a = prop, name = _a.name, initializer = _a.initializer; + return !ts.isIdentifier(name) ? undefined : convertExportsDotXEquals(name.text, initializer); + } + case 152 /* MethodDeclaration */: { + var m = prop; + return !ts.isIdentifier(m.name) ? undefined : functionExpressionToDeclaration(m.name.text, [ts.createToken(84 /* ExportKeyword */)], m); + } + default: + ts.Debug.assertNever(prop); + } + }); + } + function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + // If "originalKeywordKind" was set, this is e.g. `exports. + var text = propertyName.text; + var rename = exports.get(text); + if (rename !== undefined) { + /* + const _class = 0; + export { _class as class }; + */ + var newNodes = [ + makeConst(/*modifiers*/ undefined, rename, right), + makeExportDeclaration([ts.createExportSpecifier(rename, text)]), + ]; + changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + } + else { + changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); + } + } + function convertModuleExportsToExportDefault(exported, checker) { + var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: { + // `module.exports = function f() {}` --> `export default function f() {}` + var fn = exported; + return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; + } + case 200 /* ClassExpression */: { + // `module.exports = class C {}` --> `export default class C {}` + var cls = exported; + return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; + } + case 182 /* CallExpression */: + if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { + return convertReExportAll(exported.arguments[0], checker); + } + // falls through + default: + // `module.exports = 0;` --> `export default 0;` + return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + } + } + function convertReExportAll(reExported, checker) { + // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` + var moduleSpecifier = reExported.text; + var moduleSymbol = checker.getSymbolAtLocation(reExported); + var exports = moduleSymbol ? moduleSymbol.exports : ts.emptyUnderscoreEscapedMap; + return exports.has("export=") + ? [[reExportDefault(moduleSpecifier)], true] + : !exports.has("default") + ? [[reExportStar(moduleSpecifier)], false] + // If there's some non-default export, must include both `export *` and `export default`. + : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + } + function reExportStar(moduleSpecifier) { + return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); + } + function reExportDefault(moduleSpecifier) { + return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); + } + function convertExportsDotXEquals(name, exported) { + var modifiers = [ts.createToken(84 /* ExportKeyword */)]; + switch (exported.kind) { + case 187 /* FunctionExpression */: + case 188 /* ArrowFunction */: + // `exports.f = function() {}` --> `export function f() {}` + return functionExpressionToDeclaration(name, modifiers, exported); + case 200 /* ClassExpression */: + // `exports.C = class {}` --> `export class C {}` + return classExpressionToDeclaration(name, modifiers, exported); + default: + // `exports.x = 0;` --> `export const x = 0;` + return makeConst(modifiers, ts.createIdentifier(name), exported); + } + } + /** + * Converts `const <> = require("x");`. + * Returns nodes that will replace the variable declaration for the commonjs import. + * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. + */ + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + switch (name.kind) { + case 175 /* ObjectBindingPattern */: { + var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { + return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) + ? undefined + : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); + }); + if (importSpecifiers) { + return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + } + } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration + case 176 /* ArrayBindingPattern */: { + /* + import x from "x"; + const [a, b, c] = x; + */ + var tmp = makeUniqueName(ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + return [ + makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), + ]; + } + case 71 /* Identifier */: + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + default: + ts.Debug.assertNever(name); + } + } + /** + * Convert `import x = require("x").` + * Also converts uses like `x.y()` to `y()` and uses a named import. + */ + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + var nameSymbol = checker.getSymbolAtLocation(name); + // Maps from module property name to name actually used. (The same if there isn't shadowing.) + var namedBindingsNames = ts.createMap(); + // True if there is some non-property use like `x()` or `f(x)`. + var needDefaultImport = false; + for (var _i = 0, _a = identifiers.original.get(name.text); _i < _a.length; _i++) { + var use = _a[_i]; + if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { + // This was a use of a different symbol with the same name, due to shadowing. Ignore. + continue; + } + var parent = use.parent; + if (ts.isPropertyAccessExpression(parent)) { + var expression = parent.expression, propertyName = parent.name.text; + ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + changes.replaceNode(file, parent, ts.createIdentifier(idName)); + } + else { + needDefaultImport = true; + } + } + var namedBindings = namedBindingsNames.size === 0 ? undefined : ts.arrayFrom(ts.mapIterator(namedBindingsNames.entries(), function (_a) { + var propertyName = _a[0], idName = _a[1]; + return ts.createImportSpecifier(propertyName === idName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(idName)); + })); + if (!namedBindings) { + // If it was unused, ensure that we at least import *something*. + needDefaultImport = true; + } + return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + } + // Identifiers helpers + function makeUniqueName(name, identifiers) { + while (identifiers.original.has(name) || identifiers.additional.has(name)) { + name = "_" + name; + } + identifiers.additional.set(name, true); + return name; + } + function collectFreeIdentifiers(file) { + var map = ts.createMultiMap(); + file.forEachChild(function recur(node) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) { + map.add(node.text, node); + } + node.forEachChild(recur); + }); + return map; + } + function isFreeIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + return parent.name !== node; + case 177 /* BindingElement */: + return parent.propertyName !== node; + default: + return true; + } + } + // Node helpers + function functionExpressionToDeclaration(name, additionalModifiers, fn) { + return ts.createFunctionDeclaration(ts.getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(fn.modifiers)), ts.getSynthesizedDeepClone(fn.asteriskToken), name, ts.getSynthesizedDeepClones(fn.typeParameters), ts.getSynthesizedDeepClones(fn.parameters), ts.getSynthesizedDeepClone(fn.type), ts.convertToFunctionBody(ts.getSynthesizedDeepClone(fn.body))); + } + function classExpressionToDeclaration(name, additionalModifiers, cls) { + return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. + ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); + } + function makeSingleImport(localName, propertyName, moduleSpecifier) { + return propertyName === "default" + ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) + : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + } + function makeImport(name, namedImports, moduleSpecifier) { + var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifier)); + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); + } + function makeConst(modifiers, name, init) { + return ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, /*type*/ undefined, init)], 2 /* Const */)); + } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { + return ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, exportSpecifiers && ts.createNamedExports(exportSpecifiers), moduleSpecifier === undefined ? undefined : ts.createLiteral(moduleSpecifier)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /// /// /* @internal */ @@ -94461,14 +98355,9 @@ var ts; var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); /** * Compute the associated code actions * Exported for tests. @@ -94526,21 +98415,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); @@ -94559,7 +98448,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -94588,7 +98477,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -94649,6 +98538,14 @@ var ts; break; } } + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } if (ts.isReturnStatement(start) && !start.expression) { @@ -94875,7 +98772,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -95017,11 +98914,10 @@ var ts; case 153 /* Constructor */: return "constructor"; case 187 /* FunctionExpression */: - return scope.name - ? "function expression '" + scope.name.text + "'" - : "anonymous function expression"; case 229 /* FunctionDeclaration */: - return "function '" + scope.name.text + "'"; + return scope.name + ? "function '" + scope.name.text + "'" + : "anonymous function"; case 188 /* ArrowFunction */: return "arrow function"; case 152 /* MethodDeclaration */: @@ -95078,7 +98974,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -95106,7 +99002,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -95132,13 +99028,10 @@ var ts; var minInsertionPos = (isReadonlyArray(range.range) ? ts.last(range.range) : range.range).end; var nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ true); } else { - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { - prefix: ts.isLineBreak(file.text.charCodeAt(scope.getLastToken().pos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter, - suffix: context.newLineCharacter - }); + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } var newNodes = []; // replace range with function call @@ -95177,7 +99070,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -95250,10 +99143,12 @@ var ts; newNodes.push(call); } } - var replacementRange = isReadonlyArray(range.range) - ? { pos: ts.first(range.range).getStart(), end: ts.last(range.range).end } - : { pos: range.range.getStart(), end: range.range.end }; - changeTracker.replaceRangeWithNodes(context.file, replacementRange, newNodes, { nodeSeparator: context.newLineCharacter }); + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodesWithNodes(context.file, range.range, newNodes); + } + else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; @@ -95284,9 +99179,9 @@ var ts; var file = scope.getSourceFile(); var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); var isJS = ts.isInJavaScriptFile(scope); - var variableType = isJS + var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -95307,7 +99202,7 @@ var ts; // Declare var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); } @@ -95320,8 +99215,8 @@ var ts; var oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); if (oldVariableDeclaration) { // Declare - // CONSIDER: could detect that each is on a separate line - changeTracker.insertNodeAt(context.file, oldVariableDeclaration.getStart(), newVariableDeclaration, { suffix: ", " }); + // CONSIDER: could detect that each is on a separate line (See `extractConstant_VariableList_MultipleLines` in `extractConstants.ts`) + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); changeTracker.replaceRange(context.file, { pos: node.getStart(), end: node.end }, localReference); @@ -95339,17 +99234,10 @@ var ts; // Declare var nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); if (nodeToInsertBefore.pos === 0) { - // If we're at the beginning of the file, we need to take care not to insert before header comments - // (e.g. copyright, triple-slash references). Fortunately, this problem has already been solved - // for imports. - var insertionPos = ts.getSourceFileImportLocation(file); - changeTracker.insertNodeAt(context.file, insertionPos, newVariableStatement, { - prefix: insertionPos === 0 ? undefined : context.newLineCharacter, - suffix: ts.isLineBreak(file.text.charCodeAt(insertionPos)) ? context.newLineCharacter : context.newLineCharacter + context.newLineCharacter - }); + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ false); } else { - changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, { suffix: context.newLineCharacter + context.newLineCharacter }); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume if (node.parent.kind === 211 /* ExpressionStatement */) { @@ -95879,7 +99767,7 @@ var ts; } for (var i = 0; i < scopes.length; i++) { var scope = scopes[i]; - var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags); + var resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ false); if (resolvedSymbol === symbol) { continue; } @@ -96019,15 +99907,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { // Then it will be available via `fixCannotFindModule`. @@ -96036,8 +99920,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -96092,13 +99976,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -96115,11 +99994,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -96177,6 +100056,7 @@ var ts; })(ts || (ts = {})); /// /// +/// /// /// /// @@ -96729,9 +100609,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = ts.getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; @@ -97016,8 +100896,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -97181,7 +101060,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -97191,10 +101070,11 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, + realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); }, @@ -97333,13 +101213,13 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); @@ -97427,10 +101307,10 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -97692,13 +101572,19 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } + function getCombinedCodeFix(scope, fixId, formatOptions) { + synchronizeHostData(); + ts.Debug.assert(scope.type === "file"); + var sourceFile = getValidSourceFile(scope.fileName); + var formatContext = ts.formatting.getFormatContext(formatOptions); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); @@ -97815,7 +101701,7 @@ var ts; return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { - // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // @@ -97885,7 +101771,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -97942,6 +101827,7 @@ var ts; isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, + getCombinedCodeFix: getCombinedCodeFix, applyCodeActionCommand: applyCodeActionCommand, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, @@ -97989,19 +101875,6 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257 /* JsxAttribute */: - case 259 /* JsxSpreadAttribute */: - case 265 /* PropertyAssignment */: - case 266 /* ShorthandPropertyAssignment */: - case 152 /* MethodDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - return true; - } - return false; - } /** * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } */ @@ -98011,11 +101884,11 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: if (node.parent.kind === 145 /* ComputedPropertyName */) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } @@ -98033,20 +101906,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_9 = []; + var result_7 = []; var symbol = type.getProperty(name); if (type.flags & 131072 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_7.push(symbol); } }); - return result_9; + return result_7; } if (symbol) { - result_9.push(symbol); - return result_9; + result_7.push(symbol); + return result_7; } } return undefined; @@ -98283,8 +102156,8 @@ var ts; return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } // Set breakpoint on identifier element of destructuring pattern - // a or ...c or d: x from - // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || node.kind === 199 /* SpreadElement */ || node.kind === 265 /* PropertyAssignment */ || @@ -98426,8 +102299,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } @@ -99185,10 +103059,10 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options /*Services.FormatCodeOptions*/, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = JSON.parse(options); + var localOptions = options === undefined ? undefined : JSON.parse(options); return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); }); }; @@ -99324,7 +103198,7 @@ var ts; var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { // for now treat files as JavaScript - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -99359,8 +103233,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 40c31cebe5086..e38fc9a3910aa 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -46,24 +46,6 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); - var NodeBuilderFlags; - (function (NodeBuilderFlags) { - NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; - NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -160,7 +142,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -169,6 +151,7 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -294,6 +277,9 @@ var ts; } ts.forEach = forEach; function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -303,6 +289,19 @@ var ts; return undefined; } ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; function findAncestor(node, callback) { while (node) { var result = callback(node); @@ -319,13 +318,27 @@ var ts; ts.findAncestor = findAncestor; function zipWith(arrayA, arrayB, callback) { var result = []; - Debug.assert(arrayA.length === arrayB.length); + Debug.assertEqual(arrayA.length, arrayB.length); for (var i = 0; i < arrayA.length; i++) { result.push(callback(arrayA[i], arrayB[i], i)); } return result; } ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; function zipToMap(keys, values) { Debug.assert(keys.length === values.length); var map = createMap(); @@ -398,17 +411,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -480,11 +482,12 @@ var ts; } ts.map = map; function mapIterator(iter, mapFn) { - return { next: next }; - function next() { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; } ts.mapIterator = mapIterator; function sameMap(array, f) { @@ -545,25 +548,33 @@ var ts; return result; } ts.flatMap = flatMap; - function flatMapIter(iter, mapfn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapfn(value); - if (res) { - if (isArray(res)) { - result.push.apply(result, res); - } - else { - result.push(res); + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); } - } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; } - return result; } - ts.flatMapIter = flatMapIter; + ts.flatMapIterator = flatMapIterator; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -586,12 +597,23 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; function mapDefined(array, mapFn) { var result = []; if (array) { for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapFn(item, i); + var mapped = mapFn(array[i], i); if (mapped !== undefined) { result.push(mapped); } @@ -600,20 +622,35 @@ var ts; return result; } ts.mapDefined = mapDefined; - function mapDefinedIter(iter, mapFn) { - var result = []; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) - break; - var res = mapFn(value); - if (res !== undefined) { - result.push(res); + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } } - } - return result; + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; } - ts.mapDefinedIter = mapDefinedIter; + ts.singleIterator = singleIterator; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1253,6 +1290,8 @@ var ts; ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; function notImplemented() { throw new Error("Not implemented"); } @@ -1580,7 +1619,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47) + if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) return 3; } if (path.lastIndexOf("file:///", 0) === 0) { @@ -1647,10 +1686,6 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function moduleHasNonRelativeName(moduleName) { - return !ts.isExternalModuleNameRelative(moduleName); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -1673,7 +1708,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -1956,7 +1993,6 @@ var ts; function getSubPatternFromSpec(spec, basePath, usage, _a) { var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; var subpattern = ""; - var hasRecursiveDirectoryWildcard = false; var hasWrittenComponent = false; var components = getNormalizedPathComponents(spec, basePath); var lastComponent = lastOrUndefined(components); @@ -1971,11 +2007,7 @@ var ts; for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { var component = components_1[_i]; if (component === "**") { - if (hasRecursiveDirectoryWildcard) { - return undefined; - } subpattern += doubleAsteriskRegexFragment; - hasRecursiveDirectoryWildcard = true; } else { if (usage === "directories") { @@ -2243,10 +2275,10 @@ var ts; } function Signature() { } function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0; this.modifierFlagsCache = 0; this.transformFlags = 0; @@ -2373,9 +2405,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; function matchPatternOrExact(patternStrings, candidate) { @@ -2472,170 +2502,20 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - clearCache(); - } - else { - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - clearCache(); - } - else { - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.singleElementArray = singleElementArray; })(ts || (ts = {})); var ts; (function (ts) { @@ -2872,7 +2752,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -2900,6 +2780,9 @@ var ts; return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); } var nodeSystem = { + clearScreen: function () { + process.stdout.write("\x1Bc"); + }, args: process.argv.slice(2), newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, @@ -2978,7 +2861,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -3304,6 +3192,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3418,6 +3308,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -3472,7 +3363,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -3560,6 +3451,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3638,6 +3530,10 @@ var ts; Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2: diag(2717, ts.DiagnosticCategory.Error, "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717", "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."), Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3724,7 +3620,6 @@ var ts; The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), @@ -3775,6 +3670,7 @@ var ts; Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."), File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), @@ -3815,7 +3711,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -3922,6 +3818,9 @@ var ts; Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."), Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), + Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), + Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -3950,6 +3849,9 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -4025,9 +3927,9 @@ var ts; Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'"), Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"), Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"), + Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -4039,12 +3941,16 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), + Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"), }; })(ts || (ts = {})); var ts; (function (ts) { - ts.emptyArray = []; + ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); + ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -4064,15 +3970,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return str += " "; }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -4084,10 +3999,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -4121,12 +4036,19 @@ var ts; return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && oldResolution.resolvedFileName === newResolution.resolvedFileName && + oldResolution.originalPath === newResolution.originalPath && packageIdIsEqual(oldResolution.packageId, newResolution.packageId); } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -4297,7 +4219,7 @@ var ts; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { - if (!nodeIsSynthesized(node) && node.parent) { + if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; @@ -4695,7 +4617,7 @@ var ts; return node === parent.type; case 182: case 183: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184: return false; } @@ -5371,41 +5293,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 && node.body && node.body.kind === 234 && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -5429,7 +5340,7 @@ var ts; if (node.kind === 147) { result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { + if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } if (ts.hasJSDocNodes(node)) { @@ -5528,6 +5439,29 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208: + case 209: + case 221: + case 212: + case 222: + case 236: + case 261: + case 262: + case 223: + case 215: + case 216: + case 217: + case 213: + case 214: + case 225: + case 264: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -5840,6 +5774,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; function isESSymbolIdentifier(node) { return node.kind === 71 && node.escapedText === "Symbol"; } @@ -6251,7 +6189,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -6427,7 +6377,7 @@ var ts; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node, checkJSDoc) { - if (node.type) { + if (ts.hasType(node)) { return node.type; } if (checkJSDoc || isInJavaScriptFile(node)) { @@ -6801,14 +6751,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -7104,6 +7054,10 @@ var ts; return checker.getSignaturesOfType(type, 0).length !== 0 || checker.getSignaturesOfType(type, 1).length !== 0; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; + function forSomeAncestorDirectory(directory, callback) { + return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + } + ts.forSomeAncestorDirectory = forSomeAncestorDirectory; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -7777,7 +7731,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192; + return node.kind === 190; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -8221,7 +8175,7 @@ var ts; } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { - return ts.isIdentifier(node) && node.autoGenerateKind > 0; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; } ts.isGeneratedIdentifier = isGeneratedIdentifier; function isModifierKind(token) { @@ -8328,6 +8282,17 @@ var ts; return node && (node.kind === 154 || node.kind === 155); } ts.isAccessor = isAccessor; + function isMethodOrAccessor(node) { + switch (node.kind) { + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isMethodOrAccessor = isMethodOrAccessor; function isTypeElement(node) { var kind = node.kind; return kind === 157 @@ -8809,6 +8774,33 @@ var ts; return !!node.jsDoc && node.jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; + function hasType(node) { + return !!node.type; + } + ts.hasType = hasType; + function hasInitializer(node) { + return !!node.initializer; + } + ts.hasInitializer = hasInitializer; + function hasOnlyExpressionInitializer(node) { + return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); + } + ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257: + case 259: + case 265: + case 266: + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); var ts; (function (ts) { @@ -9215,7 +9207,7 @@ var ts; } function scanConflictMarkerTrivia(text, pos, error) { if (error) { - error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength); } var ch = text.charCodeAt(pos); var len = text.length; @@ -9439,19 +9431,60 @@ var ts; lookAhead: lookAhead, scanRange: scanRange, }; - function error(message, length) { + function error(message, errPos, length) { + if (errPos === void 0) { errPos = pos; } if (onError) { + var oldPos = pos; + pos = errPos; onError(message, length || 0); + pos = oldPos; } } + function scanNumberFragment() { + var start = pos; + var allowSeparator = false; + var isPreviousTokenSeparator = false; + var result = ""; + while (true) { + var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + result += text.substring(start, pos); + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + start = pos; + continue; + } + if (isDigit(ch)) { + allowSeparator = true; + isPreviousTokenSeparator = false; + pos++; + continue; + } + break; + } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } + return result + text.substring(start, pos); + } function scanNumber() { var start = pos; - while (isDigit(text.charCodeAt(pos))) - pos++; + var mainFragment = scanNumberFragment(); + var decimalFragment; + var scientificFragment; if (text.charCodeAt(pos) === 46) { pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; + decimalFragment = scanNumberFragment(); } var end = pos; if (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101) { @@ -9459,17 +9492,29 @@ var ts; tokenFlags |= 16; if (text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++; - if (isDigit(text.charCodeAt(pos))) { - pos++; - while (isDigit(text.charCodeAt(pos))) - pos++; - end = pos; + var preNumericPart = pos; + var finalFragment = scanNumberFragment(); + if (!finalFragment) { + error(ts.Diagnostics.Digit_expected); } else { - error(ts.Diagnostics.Digit_expected); + scientificFragment = text.substring(end, preNumericPart) + finalFragment; + end = pos; + } + } + if (tokenFlags & 512) { + var result = mainFragment; + if (decimalFragment) { + result += "." + decimalFragment; + } + if (scientificFragment) { + result += scientificFragment; } + return "" + +result; + } + else { + return "" + +(text.substring(start, end)); } - return "" + +(text.substring(start, end)); } function scanOctalDigits() { var start = pos; @@ -9478,17 +9523,35 @@ var ts; } return +(text.substring(start, pos)); } - function scanExactNumberOfHexDigits(count) { - return scanHexDigits(count, false); + function scanExactNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(count, false, canHaveSeparators); } - function scanMinimumNumberOfHexDigits(count) { - return scanHexDigits(count, true); + function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { + return scanHexDigits(count, true, canHaveSeparators); } - function scanHexDigits(minCount, scanAsManyAsPossible) { + function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { var digits = 0; var value = 0; + var allowSeparator = false; + var isPreviousTokenSeparator = false; while (digits < minCount || scanAsManyAsPossible) { var ch = text.charCodeAt(pos); + if (canHaveSeparators && ch === 95) { + tokenFlags |= 512; + if (allowSeparator) { + allowSeparator = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + allowSeparator = canHaveSeparators; if (ch >= 48 && ch <= 57) { value = value * 16 + ch - 48; } @@ -9503,10 +9566,14 @@ var ts; } pos++; digits++; + isPreviousTokenSeparator = false; } if (digits < minCount) { value = -1; } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + } return value; } function scanString(jsxAttributeString) { @@ -9642,7 +9709,7 @@ var ts; } } function scanHexadecimalEscape(numDigits) { - var escapedValue = scanExactNumberOfHexDigits(numDigits); + var escapedValue = scanExactNumberOfHexDigits(numDigits, false); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); } @@ -9652,7 +9719,7 @@ var ts; } } function scanExtendedUnicodeEscape() { - var escapedValue = scanMinimumNumberOfHexDigits(1); + var escapedValue = scanMinimumNumberOfHexDigits(1, false); var isInvalidExtendedEscape = false; if (escapedValue < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); @@ -9691,7 +9758,7 @@ var ts; if (pos + 5 < end && text.charCodeAt(pos + 1) === 117) { var start_1 = pos; pos += 2; - var value = scanExactNumberOfHexDigits(4); + var value = scanExactNumberOfHexDigits(4, false); pos = start_1; return value; } @@ -9739,8 +9806,26 @@ var ts; ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; + var separatorAllowed = false; + var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); + if (ch === 95) { + tokenFlags |= 512; + if (separatorAllowed) { + separatorAllowed = false; + isPreviousTokenSeparator = true; + } + else if (isPreviousTokenSeparator) { + error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1); + } + else { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); + } + pos++; + continue; + } + separatorAllowed = true; var valueOfCh = ch - 48; if (!isDigit(ch) || valueOfCh >= base) { break; @@ -9748,10 +9833,15 @@ var ts; value = value * base + valueOfCh; pos++; numberOfDigits++; + isPreviousTokenSeparator = false; } if (numberOfDigits === 0) { return -1; } + if (text.charCodeAt(pos - 1) === 95) { + error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); + return value; + } return value; } function scan() { @@ -9937,7 +10027,7 @@ var ts; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1); + var value = scanMinimumNumberOfHexDigits(1, true); if (value < 0) { error(ts.Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -10258,7 +10348,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -10280,6 +10370,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9: case 11: @@ -10290,55 +10381,30 @@ var ts; } return token = 5; case 64: - pos++; return token = 57; case 10: case 13: - pos++; return token = 4; case 42: - pos++; return token = 39; case 123: - pos++; return token = 17; case 125: - pos++; return token = 18; case 91: - pos++; return token = 21; case 93: - pos++; return token = 22; case 60: - pos++; return token = 27; - case 62: - pos++; - return token = 29; case 61: - pos++; return token = 58; case 44: - pos++; return token = 26; case 46: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24; - } return token = 23; - case 33: - pos++; - return token = 51; - case 63: - pos++; - return token = 55; } if (isIdentifierStart(ch, 6)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } @@ -10346,7 +10412,7 @@ var ts; return token = 71; } else { - return pos += 1, token = 0; + return token = 0; } } function speculationHelper(callback, isLookahead) { @@ -10482,20 +10548,48 @@ var ts; case 267: return visitNode(cbNode, node.expression); case 147: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 150: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 149: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); case 265: - case 227: - case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.initializer); + case 227: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); + case 177: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 161: case 162: case 156: @@ -11011,15 +11105,7 @@ var ts; if (comments) { for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDoc) { - if (!node.jsDoc) { - node.jsDoc = [jsDoc]; - } - else { - node.jsDoc.push(jsDoc); - } - } + node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); } } return node; @@ -11455,9 +11541,12 @@ var ts; return token() === 26 || token() === 24 || isIdentifierOrPattern(); case 18: return isIdentifier(); - case 11: case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); + if (token() === 26) { + return true; + } + case 11: + return token() === 24 || isStartOfExpression(); case 16: return isStartOfParameter(); case 19: @@ -11617,6 +11706,9 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -11917,7 +12009,7 @@ var ts; node.isUnterminated = true; } if (node.kind === 8) { - node.numericLiteralFlags = scanner.getTokenFlags() & 496; + node.numericLiteralFlags = scanner.getTokenFlags() & 1008; } nextToken(); finishNode(node); @@ -12860,7 +12952,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -14299,6 +14393,7 @@ var ts; switch (token()) { case 19: case 27: + case 51: case 56: case 58: case 55: @@ -14855,7 +14950,6 @@ var ts; return result; } scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; var state = 1; var margin = undefined; var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; @@ -14866,23 +14960,22 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5) { + t = nextJSDocToken(); } - if (token() === 4) { + if (t === 4) { state = 0; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1) { - switch (token()) { + loop: while (true) { + switch (t) { case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); parseTag(indent); state = 0; - advanceToken = false; margin = undefined; indent++; } @@ -14921,18 +15014,13 @@ var ts; indent += whitespace.length; break; case 1: - break; + break loop; default: state = 2; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -15016,7 +15104,8 @@ var ts; if (!tag) { return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -15029,8 +15118,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 && token() !== 1) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4: if (state >= 1) { state = 0; @@ -15039,7 +15129,9 @@ var ts; indent = 0; break; case 57: - break; + scanner.setTextPos(scanner.getTextPos() - 1); + case 1: + break loop; case 5: if (state === 2) { pushComment(scanner.getTokenText()); @@ -15055,7 +15147,7 @@ var ts; case 39: if (state === 0) { state = 1; - indent += scanner.getTokenText().length; + indent += 1; break; } default: @@ -15063,14 +15155,11 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57) { - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281, atToken.pos); @@ -15078,8 +15167,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -15148,10 +15236,7 @@ var ts; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { - if (!children) { - children = []; - } - children.push(child); + children = ts.append(children, child); } if (children) { jsdocTypeLiteral = createNode(280, start_2); @@ -15255,10 +15340,7 @@ var ts; } } else { - if (!jsdocTypeLiteral.jsDocPropertyTags) { - jsdocTypeLiteral.jsDocPropertyTags = []; - } - jsdocTypeLiteral.jsDocPropertyTags.push(child); + jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child); } } if (jsdocTypeLiteral) { @@ -15303,8 +15385,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57: if (canParseTag) { var child = tryParseChildTag(target); @@ -15344,33 +15425,43 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0; + break; case "arg": case "argument": case "param": - return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -15389,6 +15480,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -15850,12 +15949,14 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", + "esnext.promise": "lib.esnext.promise.d.ts", }), }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -16096,6 +16197,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -16376,17 +16484,17 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; function convertEnableAutoDiscoveryToEnable(typeAcquisition) { if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - var result = { + return { enable: typeAcquisition.enableAutoDiscovery, include: typeAcquisition.include || [], exclude: typeAcquisition.exclude || [] }; - return result; } return typeAcquisition; } @@ -17196,8 +17304,7 @@ var ts; return options; } function getDefaultTypeAcquisition(configFileName) { - var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - return options; + return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultTypeAcquisition(configFileName); @@ -17278,7 +17385,6 @@ var ts; return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; @@ -17361,9 +17467,6 @@ var ts; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } - else if (invalidMultipleRecursionPatterns.test(spec)) { - return ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0; - } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } @@ -17748,9 +17851,9 @@ var ts; ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations) { return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, + resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations }; } @@ -18183,8 +18286,8 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { @@ -18201,10 +18304,16 @@ var ts; if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; - if (!compilerOptions.preserveSymlinks) { - resolvedValue = resolvedValue && __assign({}, resolved_1.value, { path: realPath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }); + var originalPath = void 0; + if (!compilerOptions.preserveSymlinks && resolvedValue) { + originalPath = resolvedValue.path; + var path = realPath(resolved_1.value.path, host, traceEnabled); + if (path === originalPath) { + originalPath = undefined; + } + resolvedValue = __assign({}, resolvedValue, { path: path }); } - return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } }; + return { value: resolvedValue && { resolved: resolvedValue, originalPath: originalPath, isExternalLibraryImport: true } }; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; @@ -18239,7 +18348,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -18253,6 +18364,38 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + function parseNodeModuleFromPath(resolved) { + var path = ts.normalizePath(resolved.path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = ts.removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + ".d.ts"; + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function addExtensionAndIndex(path) { + if (path === "") { + return "index.d.ts"; + } + if (ts.endsWith(path, ".d.ts")) { + return path; + } + if (ts.endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; + } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } @@ -18326,18 +18469,41 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { - var host = _a.host, traceEnabled = _a.traceEnabled; + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + var host = state.host, traceEnabled = state.traceEnabled; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); + if (subModuleName === "") { + var path = tryReadPackageJsonFields(true, packageJsonContent, nodeModuleDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + } + else { + var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); + if (typeof jsPath === "string") { + subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js"), ".jsx") + ".d.ts"; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!ts.endsWith(subModuleName, ".d.ts")) { + subModuleName = addExtensionAndIndex(subModuleName); + } var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -18480,13 +18646,17 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -18502,7 +18672,7 @@ var ts; var failedLookupLocations = []; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, undefined, false, failedLookupLocations); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); if (resolvedUsingSettings) { @@ -18540,7 +18710,7 @@ var ts; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, undefined, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; function toSearchResult(value) { @@ -18706,34 +18876,32 @@ var ts; this.knownCachesSet.set(cacheLocation, true); }; TypingsInstaller.prototype.filterTypings = function (typingsToInstall) { - if (typingsToInstall.length === 0) { - return typingsToInstall; - } - var result = []; - for (var _i = 0, typingsToInstall_1 = typingsToInstall; _i < typingsToInstall_1.length; _i++) { - var typing = typingsToInstall_1[_i]; - if (this.missingTypingsSet.get(typing) || this.packageNameToTypingLocation.get(typing)) { - continue; + var _this = this; + return typingsToInstall.filter(function (typing) { + if (_this.missingTypingsSet.get(typing)) { + if (_this.log.isEnabled()) + _this.log.writeLine("'" + typing + "' is in missingTypingsSet - skipping..."); + return false; + } + if (_this.packageNameToTypingLocation.get(typing)) { + if (_this.log.isEnabled()) + _this.log.writeLine("'" + typing + "' already has a typing - skipping..."); + return false; } var validationResult = ts.JsTyping.validatePackageName(typing); - if (validationResult === 0) { - if (this.typesRegistry.has(typing)) { - result.push(typing); - } - else { - if (this.log.isEnabled()) { - this.log.writeLine("Entry for package '" + typing + "' does not exist in local types registry - skipping..."); - } - } + if (validationResult !== 0) { + _this.missingTypingsSet.set(typing, true); + if (_this.log.isEnabled()) + _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing)); + return false; } - else { - this.missingTypingsSet.set(typing, true); - if (this.log.isEnabled()) { - this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing)); - } + if (!_this.typesRegistry.has(typing)) { + if (_this.log.isEnabled()) + _this.log.writeLine("Entry for package '" + typing + "' does not exist in local types registry - skipping..."); + return false; } - } - return result; + return true; + }); }; TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) { var npmConfigPath = ts.combinePaths(directory, "package.json"); diff --git a/lib/zh-CN/diagnosticMessages.generated.json b/lib/zh-CN/diagnosticMessages.generated.json index e7713b2cbd3be..1fb25de397b36 100644 --- a/lib/zh-CN/diagnosticMessages.generated.json +++ b/lib/zh-CN/diagnosticMessages.generated.json @@ -12,11 +12,11 @@ "A_class_member_cannot_have_the_0_keyword_1248": "类成员不可具有“{0}”关键字。", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "计算属性名中不允许逗号表达式。", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "计算属性名无法从其包含的类型引用类型参数。", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "类属性声明中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", - "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "方法重载中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "类型文本中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", - "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "环境上下文中的计算属性名称必须引用类型为文本类型或“唯一符号”类型的表达式。", - "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "接口中的计算属性名称必须引用必须引用类型为文本类型或“唯一符号”的表达式。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "类属性声明中的计算属性名称必须引用类型为文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "方法重载中的计算属性名称必须引用文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "类型文本中的计算属性名称必须引用类型为文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "环境上下文中的计算属性名称必须引用类型为文本类型或 \"unique symbol\" 类型的表达式。", + "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "接口中的计算属性名称必须引用必须引用类型为文本类型或 \"unique symbol\" 的表达式。", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "计算属性名的类型必须为 \"string\"、\"number\"、\"symbol\" 或 \"any\"。", "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471": "窗体“{0}”的计算属性名必须是 \"symbol\" 类型。", "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476": "只有使用字符串文本才能访问常数枚举成员。", @@ -48,14 +48,15 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空间声明必须位于与之合并的类或函数所在的相同文件内。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空间声明不能位于与之合并的类或函数前", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只允许在命名空间或模块中使用命名空间声明。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "命名空间样式导入不能调用或构造,并将在运行时导致失败。", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只允许在函数或构造函数实现中使用参数初始化表达式。", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "不能使用 rest 参数声明参数属性。", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "只允许在构造函数实现中使用参数属性。", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "不能使用绑定模式声明参数属性。", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "“扩展”选项中的路径必须为相对路径或根路径,但“{0}”不是。", "A_promise_must_have_a_then_method_1059": "承诺必须具有 \"then\" 方法。", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "类型为“唯一符号”的类的属性必须同时为“静态”和“只读”。", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "类型为“唯一符号”的接口或类型文本的属性必须是“只读”", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "类型为 \"unique symbol\" 的类的属性必须同时为 \"static\" 和 \"readonly\"。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "类型为 \"unique symbol\" 的接口或类型文本的属性必须为 \"readonly\"。", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必选参数不能位于可选参数后。", "A_rest_element_cannot_contain_a_binding_pattern_2501": "rest 元素不能包含绑定模式。", "A_rest_element_cannot_have_an_initializer_1186": "rest 元素不能具有初始化表达式。", @@ -83,7 +84,7 @@ "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230": "类型谓词无法在绑定模式中引用元素“{0}”。", "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228": "只允许在函数和方法的返回类型位置使用类型谓词。", "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677": "类型谓词的类型不可赋给其参数的类型。", - "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "类型为“唯一符号”的变量必须是“常量”。", + "A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332": "类型为 \"unique symbol\" 的变量必须为 \"const\"。", "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": "抽象方法只能出现在抽象类中。", @@ -91,11 +92,12 @@ "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": "两个取值函数必须都是抽象的或都是非抽象的。", - "Add_0_to_existing_import_declaration_from_1_90015": "将 {0} 从 {1} 添加到现有导入声明。", - "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名。", - "Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用。", - "Add_this_to_unresolved_variable_90008": "向未解析的变量添加 \"this.\"。", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "添加 tsconfig.json 文件有助于组织包含 TypeScript 和 JavaScript 文件的项目。有关详细信息,请访问 https://aka.ms/tsconfig。", + "Add_0_to_existing_import_declaration_from_1_90015": "将“{0}”从“{1}”添加到现有导入声明", + "Add_async_modifier_to_containing_function_90029": "将异步修饰符添加到包含函数", + "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名", + "Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用", + "Add_this_to_unresolved_variable_90008": "向未解析的变量添加 \"this.\"", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "添加 tsconfig.json 文件有助于组织包含 TypeScript 和 JavaScript 文件的项目。有关详细信息,请访问 https://aka.ms/tsconfig。", "Additional_Checks_6176": "其他检查", "Advanced_Options_6178": "高级选项", "All_declarations_of_0_must_have_identical_modifiers_2687": "“{0}”的所有声明必须具有相同的修饰符。", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改而编写“[{0}: {1}]:{2}”。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", "An_interface_may_only_extend_a_class_or_another_interface_2312": "接口只能扩展类或其他接口。", @@ -147,7 +151,7 @@ "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_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}。", @@ -165,7 +169,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_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}”属性的类型?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "无法导入类型声明文件。请考虑导入“{0}”,而不是“{1}”。", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "无法在块范围声明“{1}”所在的范围内初始化外部范围变量“{0}”。", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "无法调用类型缺少调用签名的表达式。类型“{0}”没有兼容的调用签名。", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "不能调用可能是 \"null\" 的对象。", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "不能调用可能是 \"null\" 或“未定义”的对象。", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "不能调用可能是“未定义”的对象。", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "提供 \"--isolatedModules\" 标记时无法重新导出类型。", "Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "将 \"extends\" 更改为 \"implements\"。", - "Change_spelling_to_0_90022": "将拼写更改为“{0}”。", + "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}”的最长匹配前缀。", "Circular_definition_of_import_alias_0_2303": "导入别名“{0}”的循环定义。", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "解析配置时检测到循环: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "类“{0}”将“{1}”定义为实例成员函数,但扩展类“{2}”将其定义为实例成员属性。", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "类“{0}”将“{1}”定义为实例成员属性,但扩展类“{2}”将其定义为实例成员函数。", "Class_0_incorrectly_extends_base_class_1_2415": "类“{0}”错误扩展基类“{1}”。", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "类“{0}”错误实现类“{1}”。你是想扩展“{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\" 标记。", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。", "Convert_function_0_to_class_95002": "将函数“{0}”转换为类", "Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类", + "Convert_to_ES6_module_95017": "转换为 ES6 模块", "Convert_to_default_import_95013": "转换为默认导入", "Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "无法找到模块“{0}”的声明文件。“{1}”隐式拥有 \"any\" 类型。", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "应为声明。", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "声明名称与内置全局标识符“{0}”冲突。", "Declaration_or_statement_expected_1128": "应为声明或语句。", - "Declare_method_0_90023": "声明方法“{0}”。", - "Declare_property_0_90016": "声明属性“{0}”。", - "Declare_static_method_0_90024": "声明静态方法“{0}”。", - "Declare_static_property_0_90027": "声明静态属性 \"{0}\"。", + "Declare_method_0_90023": "声明方法“{0}”", + "Declare_property_0_90016": "声明属性“{0}”", + "Declare_static_method_0_90024": "声明静态方法“{0}”", + "Declare_static_property_0_90027": "声明静态属性“{0}”", "Decorators_are_not_valid_here_1206": "修饰器在此处无效。", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "不能向多个同名的 get/set 访问器应用修饰器。", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模块的默认导出具有或正在使用专用名称“{0}”。", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[已弃用] 请改用 \"--skipLibCheck\"。请跳过默认库声明文件的类型检查。", "Digit_expected_1124": "应为数字。", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "目录“{0}”不存在,正在跳过该目录中的所有查找。", - "Disable_checking_for_this_file_90018": "禁用检查此文件。", + "Disable_checking_for_this_file_90018": "禁用检查此文件", "Disable_size_limitations_on_JavaScript_projects_6162": "禁用对 JavaScript 项目的大小限制。", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "禁止严格检查函数类型中的通用签名。", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "不允许对同一文件采用大小不一致的引用。", @@ -309,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。", "Enable_strict_null_checks_6113": "启用严格的 NULL 检查。", "Enable_tracing_of_the_name_resolution_process_6085": "启用名称解析过程的跟踪。", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "通过为所有导入创建命名空间对象来启用 CommonJS 和 ES 模块之间的发出互操作性。表示 \"allowSyntheticDefaultImports\"。", "Enables_experimental_support_for_ES7_async_functions_6068": "对 ES7 异步函数启用实验支持。", "Enables_experimental_support_for_ES7_decorators_6065": "对 ES7 修饰器启用实验支持。", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "对发出修饰器的类型元数据启用实验支持。", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "文件名“{0}”仅在大小写方面与包含的文件名“{1}”不同。", "File_name_0_has_a_1_extension_stripping_it_6132": "文件名“{0}”的扩展名为“{1}”,请去除它。", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "文件规范不能包含出现在递归目录通配符(\"*\"): “{0}”后的父目录(\"..\")。", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "文件规范不能包含多个递归目录通配符(\"**\"):“{0}”。", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "文件规范不能以递归目录通配符结尾(\"**\"):“{0}”。", "Found_package_json_at_0_6099": "在“{0}”处找到了 \"package.json\"。", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "面向 \"ES3\" 或 \"ES5\" 时,在严格模式下,块内不允许函数声明。", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "应为标识符。“{0}”是严格模式下的保留字。模块自动处于严格模式。", "Identifier_expected_1003": "应为标识符。", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "应为标识符。转换 ECMAScript 模块时,\"__esModule\" 保留为导出标记。", - "Ignore_this_error_message_90019": "忽略此错误信息。", - "Implement_inherited_abstract_class_90007": "实现继承的抽象类。", - "Implement_interface_0_90006": "实现接口“{0}”。", + "Ignore_this_error_message_90019": "忽略此错误信息", + "Implement_inherited_abstract_class_90007": "实现已继承的抽象类", + "Implement_interface_0_90006": "实现接口“{0}”", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "导出的类“{0}”的 Implements 子句具有或正在使用专用名称“{1}”。", - "Import_0_from_module_1_90013": "从模块“{1}”导入“{0}”。", + "Import_0_from_module_1_90013": "从模块“{1}”导入“{0}”", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "面向 ECMAScript 模块时,不能使用导入分配。请考虑改用 \"import * as ns from \"mod\"\"、\"import {a} from \"mod\"\"、\"import d from \"mod\"\" 或另一种模块格式。", "Import_declaration_0_is_using_private_name_1_4000": "导入声明“{0}”使用的是专用名称“{1}”。", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "导入声明与“{0}”的局部声明冲突。", @@ -424,10 +433,10 @@ "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}”。", + "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}”。", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "参数“{0}”的初始化表达式不能引用在它之后声明的标识符“{1}”。", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始化表达式没有为此绑定元素提供此任何值,且该绑定元素没有默认值。", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "区域设置必须采用 <语言> 或 <语言>-<区域> 形式。例如“{0}”或“{1}”。", "Longest_matching_prefix_for_0_is_1_6108": "“{0}”的最长匹配前缀为“{1}”。", "Looking_up_in_node_modules_folder_initial_location_0_6125": "正在在 \"node_modules\" 文件夹中查找,初始位置“{0}”。", - "Make_super_call_the_first_statement_in_the_constructor_90002": "在构造函数中,使 \"super()\" 调用第一个语句。", + "Make_super_call_the_first_statement_in_the_constructor_90002": "在构造函数中,使 \"super()\" 调用第一个语句", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "映射的对象类型隐式地含有 \"any\" 模板类型。", "Member_0_implicitly_has_an_1_type_7008": "成员“{0}”隐式包含类型“{1}”。", "Merge_conflict_marker_encountered_1185": "遇到合并冲突标记。", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合并声明“{0}”不能包含默认导出声明。请考虑改为添加一个独立的“导出默认 {0}”声明。", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模块名“{0}”已成功解析为“{1}”。========", "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模块解析类型,正在使用“{0}”。", "Module_resolution_using_rootDirs_has_failed_6111": "使用 \"rootDirs\" 的模块解析失败。", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允许使用多个连续的数字分隔符。", "Multiple_constructor_implementations_are_not_allowed_2392": "不允许存在多个构造函数实现。", "NEWLINE_6061": "换行符", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "“{1}”和“{2}”类型的命名属性“{0}”不完全相同。", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象类表达式不会实现继承自“{1}”类的抽象成员“{0}”。", "Not_all_code_paths_return_a_value_7030": "并非所有代码路径都返回值。", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "数字索引类型“{0}”不能赋给字符串索引类型“{1}”。", + "Numeric_separators_are_not_allowed_here_6188": "此处不允许使用数字分隔符。", "Object_is_possibly_null_2531": "对象可能为 \"null\"。", "Object_is_possibly_null_or_undefined_2533": "对象可能为 \"null\" 或“未定义”。", "Object_is_possibly_undefined_2532": "对象可能为“未定义”。", @@ -584,7 +596,7 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "导出类中的公共静态 setter“{0}”的参数类型具有或正在使用专用名称“{1}”。", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "以严格模式进行分析,并为每个源文件发出 \"use strict\" 指令。", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "模式“{0}”最多只可具有一个 \"*\" 字符。", - "Prefix_0_with_an_underscore_90025": "带下划线的前缀“{0}”。", + "Prefix_0_with_an_underscore_90025": "带下划线的前缀“{0}”", "Print_names_of_files_part_of_the_compilation_6155": "属于编译一部分的文件的打印名称。", "Print_names_of_generated_files_part_of_the_compilation_6154": "属于编译一部分的已生成文件的打印名称。", "Print_the_compiler_s_version_6019": "打印编译器的版本。", @@ -596,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "属性“{0}”没有初始化表达式,且未在构造函数中明确赋值。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "属性“{0}”隐式具有类型 \"any\",因为其 get 访问器缺少返回类型批注。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "属性“{0}”隐式具有类型 \"any\",因为其 set 访问器缺少参数类型批注。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "类型“{1}”中的属性“{0}”不可分配给基类型“{2}”中的同一属性。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "类型“{1}”中的属性“{0}”不可分配给类型“{2}”。", "Property_0_is_declared_but_its_value_is_never_read_6138": "已声明属性“{0}”,但从未读取其值。", "Property_0_is_incompatible_with_index_signature_2530": "属性“{0}”与索引签名不兼容。", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "对具有隐式 \"any\" 类型的表达式和声明引发错误。", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。", "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", - "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明。", + "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明", + "Replace_import_with_0_95015": "用“{0}”替换导入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。", "Report_errors_in_js_files_8019": ".js 文件中的报表出错。", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "导出类中的公共静态方法的返回类型具有或正在使用专用名称“{0}”。", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "重用源自“{0}”的模块解析,因为解析在旧程序中未更改。", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "对文件“{1}”重用旧程序中模块 “{0}”的解析。", - "Rewrite_as_the_indexed_access_type_0_90026": "重写为索引访问类型“{0}”。", + "Rewrite_as_the_indexed_access_type_0_90026": "重写为索引访问类型“{0}”", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "无法确定根目录,正在跳过主搜索路径。", "STRATEGY_6039": "策略", "Scoped_package_detected_looking_in_0_6182": "检测到范围包,请在“{0}”中查看", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "源映射选项", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "指定的重载签名不可分配给任何非专用化签名。", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "动态导入的说明符不能是扩散元素。", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "指定 ECMAScript 目标版本: \"ES3\"(默认)、\"ES5\"、\"ES2015\"、\"ES2016\"、\"ES2017\" 或 \"ESNEXT\"。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "指定 ECMAScript 目标版本: \"ES3\" (默认)、\"ES5\"、\"ES2015\"、\"ES2016\"、\"ES2017\"、\"ES2018\" 或 \"ESNEXT\"。", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "指定 JSX 代码生成: \"preserve\"、\"react-native\" 或 \"react\"。", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "指定要在编译中包括的库文件: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "指定模块代码生成: \"none\"、\"commonjs\"、\"amd\"、\"system\"、\"umd\"、\"es2015\"或 \"ESNext\"。", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定输入文件的根目录。与 --outDir 一起用于控制输出目录结构。", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "仅当面向 ECMAScript 5 和更高版本时,\"new\" 表达式中的展开运算符才可用。", "Spread_types_may_only_be_created_from_object_types_2698": "spread 类型只能从对象类型创建。", + "Starting_compilation_in_watch_mode_6031": "在监视模式下开始编译...", "Statement_expected_1129": "应为语句。", "Statements_are_not_allowed_in_ambient_contexts_1036": "不允许在环境上下文中使用语句。", "Static_members_cannot_reference_class_type_parameters_2302": "静态成员不能引用类类型参数。", @@ -713,7 +728,7 @@ "String_literal_expected_1141": "应为字符串文本。", "String_literal_with_double_quotes_expected_1327": "应为带双引号的字符串文字。", "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "使用颜色和上下文风格化错误和消息(实验)。", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "后续属性声明必须属于同一类型。属性“{0}”的类型必须为“{1}”,但此处却为类型“{2}”。", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "后续变量声明必须属于同一类型。变量“{0}”必须属于类型“{1}”,但此处却为类型“{2}”。", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "模式“{1}”的替换“{0}”类型不正确,应为 \"string\",实际为“{2}”。", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "模式“{1}”中的替换“{0}”最多只可具有一个 \"*\" 字符。", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "类型“{0}”不是数组类型或字符串类型,或者没有返回迭代器的 \"[Symbol.iterator]()\" 方法。", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "类型“{0}”不是数组类型,或者没有返回迭代器的 \"[Symbol.iterator]()\" 方法。", "Type_0_is_not_assignable_to_type_1_2322": "不能将类型“{0}”分配给类型“{1}”。", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "类型“{0}”无法分配给类型“{1}”。存在具有此名称的两种不同类型,但它们是不相关的。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "类型“{0}”无法分配给类型“{1}”。存在具有此名称的两种不同类型,但它们是不相关的。", "Type_0_is_not_comparable_to_type_1_2678": "类型“{0}”不可与类型“{1}”进行比较。", "Type_0_is_not_generic_2315": "类型“{0}”不是泛型类型。", "Type_0_provides_no_match_for_the_signature_1_2658": "类型“{0}”提供的内容与签名“{1}”不匹配。", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "未终止的模板文本。", "Untyped_function_calls_may_not_accept_type_arguments_2347": "非类型化函数调用不能接受类型参数。", "Unused_label_7028": "未使用的标签。", + "Use_synthetic_default_member_95016": "使用综合的“默认”成员。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "仅 ECMAScript 5 和更高版本支持在 \"for...of\" 语句中使用字符串。", "VERSION_6036": "版本", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "类型“{0}”的值没有与类型“{1}”相同的属性。你是想调用它吗?", @@ -913,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "必须初始化 \"const\" 声明。", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "\"const\" 枚举成员初始化表达式的求值结果为非有限值。", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "\"const\" 枚举成员初始化表达式的求值结果为不允许使用的值 \"NaN\"。", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "\"const\" 枚举仅可在属性、索引访问表达式、导入声明的右侧或导出分配中使用。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "\"const\" 枚举仅可在属性、索引访问表达式、导入声明的右侧、导出分配或类型查询中使用。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "在严格模式下,无法对标识符调用 \"delete\"。", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" 只能在 .ts 文件中使用。", "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" 只能在 .ts 文件中使用。", @@ -941,7 +957,7 @@ "package_json_has_0_field_1_that_references_2_6101": "\"package.json\" 具有引用“{2}”的“{0}”字段“{1}”。", "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" 只能在 .ts 文件中使用。", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "指定了 \"paths“ 选项,正在查找模式以匹配模块名“{0}”。", - "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 仅可出现在属性声明或索引签名中。", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 修饰符仅可出现在属性声明或索引签名中。", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "设置了 \"rootDirs\" 选项,可将其用于解析相对模块名称“{0}”。", "super_can_only_be_referenced_in_a_derived_class_2335": "只能在派生类中引用 \"super\"。", "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "仅可在派生类或对象文字表达式的成员中引用 \"super\"。", @@ -963,9 +979,9 @@ "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016": "\"type assertion expressions\" 只能在 .ts 文件中使用。", "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004": "\"type parameter declarations\" 只能在 .ts 文件中使用。", "types_can_only_be_used_in_a_ts_file_8010": "\"types\" 只能在 .ts 文件中使用。", - "unique_symbol_types_are_not_allowed_here_1335": "此处不允许“唯一符号”类型。", - "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "“唯一符号”类型仅可在变量语句中的变量上使用。", - "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "不可在具有绑定名称的变量声明中使用“唯一符号”类型。", + "unique_symbol_types_are_not_allowed_here_1335": "此处不允许使用 \"unique symbol\" 类型。", + "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334": "\"unique symbol\" 类型仅可用于变量语句中的变量。", + "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333": "不可在具有绑定名称的变量声明中使用 \"unique symbol\" 类型。", "with_statements_are_not_allowed_in_an_async_function_block_1300": "不允许在异步函数块中使用 \"with\" 语句。", "with_statements_are_not_allowed_in_strict_mode_1101": "严格模式下不允许使用 \"with\" 语句。", "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "不能在参数初始化表达式中使用 \"yield\" 表达式。" diff --git a/lib/zh-TW/diagnosticMessages.generated.json b/lib/zh-TW/diagnosticMessages.generated.json index 39a6a077fbf49..fedb82499f441 100644 --- a/lib/zh-TW/diagnosticMessages.generated.json +++ b/lib/zh-TW/diagnosticMessages.generated.json @@ -12,9 +12,9 @@ "A_class_member_cannot_have_the_0_keyword_1248": "類別成員不能含有 '{0}' 關鍵字。", "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171": "計算的屬性名稱中不可有逗點運算式。", "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467": "計算的屬性名稱不得參考其包含類型中的型別參數。", - "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "類別屬性宣告中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166": "類別屬性宣告中的計算屬性名稱,必須參考類型為常值型別或 'unique symbol' 類型的運算式。", "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168": "方法多載中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", - "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "型別常值中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", + "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170": "常值型別中的計算屬性名稱,必須參考類型為常值型別或 'unique symbol' 類型的運算式。", "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165": "環境內容中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169": "介面中的計算屬性名稱必須參考型別為常值型別或 'unique symbol' 型別的運算式。", "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464": "計算的屬性名稱必須是 'string'、'number'、'symbol' 或 'any' 類型。", @@ -48,14 +48,15 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空間宣告的所在檔案位置,不得與其要合併的類別或函式不同。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空間宣告的位置不得先於其要合併的類別或函式。", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只有命名空間或模組才允許命名空間宣告。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "命名空間樣式的匯入無法加以呼叫或建構,而且會導致執行階段失敗。", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只有函式或建構函式實作才可使用參數初始設定式。", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "無法使用剩餘參數宣告參數屬性。", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "建構函式實作中只可有一個參數屬性。", "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187": "無法使用繫結模式宣告參數屬性。", "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001": "[擴充] 選項中的路徑必須為相對或根路徑,但 '{0}' 並不是。", "A_promise_must_have_a_then_method_1059": "Promise 必須有 'then' 方法。", - "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "型別為 'unique symbol' 型別的類別屬性必須同時為 'static' 與 'readonly'。", - "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "型別為 'unique symbol' 型別的介面或型別常值屬性必須是 'readonly'。", + "A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331": "類型為 'unique symbol' 類型的類別屬性,必須為 'static' 和 'readonly'。", + "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "類型為 'unique symbol' 類型之介面或常值型別的屬性,必須是 'readonly'。", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "必要參數不得接在選擇性參數之後。", "A_rest_element_cannot_contain_a_binding_pattern_2501": "剩餘項目不得包含繫結模式。", "A_rest_element_cannot_have_an_initializer_1186": "剩餘項目不得有初始設定式。", @@ -91,11 +92,12 @@ "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": "存取子必須兩者均為抽象或非抽象。", - "Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告。", - "Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章。", - "Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫。", - "Add_this_to_unresolved_variable_90008": "將 'this.' 新增到未經解析的變數。", - "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。如需深入了解,請參閱 https://aka.ms/tsconfig。", + "Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告", + "Add_async_modifier_to_containing_function_90029": "將 async 修飾詞新增至包含的函式", + "Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章", + "Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫", + "Add_this_to_unresolved_variable_90008": "將 'this' 新增至未解析的變數", + "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。若要深入了解,請前往 https://aka.ms/tsconfig。", "Additional_Checks_6176": "其他檢查", "Advanced_Options_6178": "進階選項", "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引簽章參數不得有存取範圍修飾詞。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引簽章參數不得有初始設定式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引簽章參數必須有類型註釋。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引簽章參數類型不能是類型別名。請考慮改為撰寫 '[{0}: {1}]: {2}'。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引簽章參數類型不能是等位型別。請考慮改用對應的物件類型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引簽章參數類型必須是 'string' 或 'number'。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "介面只能擴充具有選擇性型別引數的識別碼/限定名稱。", "An_interface_may_only_extend_a_class_or_another_interface_2312": "每個介面只可擴充一個類別或另一個介面。", @@ -165,7 +169,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_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}' 的類型嗎?", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "無法匯入型別宣告檔案。請考慮匯入 '{0}' 而不是 '{1}'。", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "無法初始化區塊範圍宣告 '{1}' 之同一範圍中的外部範圍變數 '{0}'。", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "無法叫用類型缺少呼叫簽章的運算式。類型 '{0}' 不含相容的呼叫簽章。", + "Cannot_invoke_an_object_which_is_possibly_null_2721": "無法叫用可能為 'null' 的物件。", + "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "無法叫用可能為 'null' 或 'undefined' 的物件。", + "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "無法叫用可能為 'undefined' 的物件。", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "如有提供 '--isolatedModules' 旗標,即無法重新匯出類型。", "Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。", @@ -210,9 +217,9 @@ "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_extends_to_implements_90003": "將 'extends' 變更為 'implements'。", - "Change_spelling_to_0_90022": "將拼字變更為 '{0}'。", + "Change_0_to_1_90014": "將 '{0}' 變更為 '{1}'", + "Change_extends_to_implements_90003": "將 [延伸] 變更至 [實作]5D;", + "Change_spelling_to_0_90022": "將拼字變更為 '{0}'", "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104": "檢查 '{0}' 是否為 '{1}' - '{2}' 的最長相符前置詞。", "Circular_definition_of_import_alias_0_2303": "匯入別名 '{0}' 的循環定義。", "Circularity_detected_while_resolving_configuration_Colon_0_18000": "解析組態時偵測到循環性: {0}", @@ -221,6 +228,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "類別 '{0}' 已定義執行個體成員函式 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員屬性。", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "類別 '{0}' 已定義執行個體成員屬性 '{1}',但是擴充類別 '{2}' 卻將其定義為執行個體成員函式。", "Class_0_incorrectly_extends_base_class_1_2415": "類別 '{0}' 不正確地擴充基底類別 '{1}'。", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "類別 '{0}' 不當實作類別 '{1}'。您是否要擴充 '{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' 標記。", @@ -245,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。", "Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別", "Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別", + "Convert_to_ES6_module_95017": "轉換為 ES6 模組", "Convert_to_default_import_95013": "轉換為預設匯入", "Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "找不到模組 '{0}' 的宣告檔案。'{1}' 隱含具有 'any' 類型。", @@ -253,10 +262,10 @@ "Declaration_expected_1146": "必須是宣告。", "Declaration_name_conflicts_with_built_in_global_identifier_0_2397": "宣告名稱與內建全域識別碼 '{0}' 衝突。", "Declaration_or_statement_expected_1128": "必須是宣告或陳述式。", - "Declare_method_0_90023": "宣告方法 '{0}'。", - "Declare_property_0_90016": "宣告屬性 '{0}'。", - "Declare_static_method_0_90024": "宣告靜態方法 '{0}'。", - "Declare_static_property_0_90027": "宣告靜態屬性 '{0}'。", + "Declare_method_0_90023": "宣告方法 '{0}'", + "Declare_property_0_90016": "宣告屬性 '{0}'", + "Declare_static_method_0_90024": "宣告靜態方法 '{0}'", + "Declare_static_property_0_90027": "宣告靜態屬性 '{0}'", "Decorators_are_not_valid_here_1206": "裝飾項目在此處無效。", "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "無法將裝飾項目套用至多個同名的 get/set 存取子。", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模組的預設匯出具有或正在使用私用名稱 '{0}'。", @@ -265,7 +274,7 @@ "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[即將淘汰] 請改用 '--skipLibCheck'。跳過預設程式庫宣告檔案的類型檢查。", "Digit_expected_1124": "必須是數字。", "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148": "目錄 '{0}' 不存在,將會跳過其中所有查閱。", - "Disable_checking_for_this_file_90018": "停用此檔案的檢查。", + "Disable_checking_for_this_file_90018": "停用此檔案的檢查", "Disable_size_limitations_on_JavaScript_projects_6162": "停用 JavaScript 專案的大小限制。", "Disable_strict_checking_of_generic_signatures_in_function_types_6185": "停用函式類型中一般簽章的 Strict 檢查。", "Disallow_inconsistently_cased_references_to_the_same_file_6078": "不允許相同檔案大小寫不一致的參考。", @@ -309,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。", "Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。", "Enable_tracing_of_the_name_resolution_process_6085": "啟用名稱解析流程的追蹤。", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "透過為所有匯入建立命名空間物件,讓 CommonJS 和 ES 模組之間的產出有互通性。意指 'allowSyntheticDefaultImports'。", "Enables_experimental_support_for_ES7_async_functions_6068": "啟用 ES7 非同步函式的實驗支援。", "Enables_experimental_support_for_ES7_decorators_6065": "啟用 ES7 裝飾項目的實驗支援。", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "啟用實驗支援以發出裝飾項目類型的中繼資料。", @@ -348,7 +358,7 @@ "Expression_or_comma_expected_1137": "必須是運算式或逗號。", "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "運算式會解析成 '_super',而編譯器會使用其來擷取基底類別參考。", "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521": "運算式會解析成變數宣告 '{0}',而編譯器會使用此宣告支援非同步函式。", - "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "運算式解析成編譯器用來擷取 'new.target' 中繼屬性參考的變數宣告 '_newTarget'。", + "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544": "運算式將解析成變數宣告 '_newTarget',而供編譯器用來擷取 'new.target' 中繼屬性參考。", "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400": "運算式會解析成變數宣告 '_this',而編譯器會使用此宣告來擷取 'this' 參考 。", "Extract_constant_95006": "解壓縮常數", "Extract_function_95005": "解壓縮函式", @@ -371,7 +381,6 @@ "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149": "檔案名稱 '{0}' 與包含的檔案名稱 '{1}' 只差在大小寫。", "File_name_0_has_a_1_extension_stripping_it_6132": "檔案名稱 '{0}' 的副檔名為 '{1}'。正予以移除。", "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065": "檔案規格不得包含出現在遞迴目錄萬用字元 ('**') 之後的父目錄 ('..'): '{0}'。", - "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011": "檔案規格不能包含多個遞迴目錄萬用字元 ('**'): '{0}'。", "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010": "檔案規格不能以遞迴目錄萬用字元 ('**') 結尾: '{0}'。", "Found_package_json_at_0_6099": "在 '{0}' 找到 'package.json'。", "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250": "以 'ES3' 或 'ES5' 為目標時,strict 模式下的區塊中不允許函式宣告。", @@ -404,11 +413,11 @@ "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214": "需要識別碼。'{0}' 是 strict 模式中的保留字。模組會自動採用 strict 模式。", "Identifier_expected_1003": "必須是識別碼。", "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216": "必須有識別碼。'__esModule' 已保留為轉換 ECMAScript 模組時匯出的標記。", - "Ignore_this_error_message_90019": "忽略此錯誤訊息。", - "Implement_inherited_abstract_class_90007": "實作已繼承的抽象類別。", - "Implement_interface_0_90006": "實作介面 '{0}'。", + "Ignore_this_error_message_90019": "略過此錯誤訊息", + "Implement_inherited_abstract_class_90007": "實作已繼承的抽象類別", + "Implement_interface_0_90006": "實作介面 '{0}'", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "匯出類別 '{0}' 的 Implements 子句具有或使用私用名稱 '{1}'。", - "Import_0_from_module_1_90013": "從模組 \"{1}\" 匯入 '{0}'。", + "Import_0_from_module_1_90013": "從模組 \"{1}\" 匯入 '{0}'", "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "當目標為 ECMAScript 模組時,無法使用匯入指派。請考慮改用 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' 或其他模組格式。", "Import_declaration_0_is_using_private_name_1_4000": "匯入宣告 '{0}' 使用私用名稱 '{1}'。", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "匯入宣告與 '{0}' 的區域宣告衝突。", @@ -424,10 +433,10 @@ "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}'。", + "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}'。", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "參數 '{0}' 的初始設定式不得參考在其之後宣告的識別碼 '{1}'。", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始設定式未提供任何值給這個繫結項目,且該繫結項目沒有預設值。", @@ -484,7 +493,8 @@ "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048": "地區設定的格式必須是 <語言> 或 <語言>-<國家/地區>。例如 '{0}' 或 '{1}'。", "Longest_matching_prefix_for_0_is_1_6108": "符合 '{0}' 的前置詞最長為 '{1}'。", "Looking_up_in_node_modules_folder_initial_location_0_6125": "目前正在 'node_modules' 資料夾中查詢,初始位置為 '{0}'。", - "Make_super_call_the_first_statement_in_the_constructor_90002": "使 'super()' 呼叫成為建構函式中的第一個陳述式。", + "Make_super_call_the_first_statement_in_the_constructor_90002": "使 'super()' 呼叫成為建構函式中的第一個陳述式", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "對應的物件類型隱含具有 'any' 範本類型。", "Member_0_implicitly_has_an_1_type_7008": "成員 '{0}' 隱含了 '{1}' 類型。", "Merge_conflict_marker_encountered_1185": "偵測到合併衝突標記。", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合併宣告 '{0}' 不得包含預設匯出宣告。請考慮改為加入獨立型 'export default {0}' 宣告。", @@ -508,6 +518,7 @@ "Module_name_0_was_successfully_resolved_to_1_6089": "======== 模組名稱 '{0}' 已成功解析為 '{1}'。========", "Module_resolution_kind_is_not_specified_using_0_6088": "未指定模組解析種類,將使用 '{0}'。", "Module_resolution_using_rootDirs_has_failed_6111": "使用 'rootDirs' 解析模組失敗。", + "Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允許多個連續的數字分隔符號。", "Multiple_constructor_implementations_are_not_allowed_2392": "不允許多個建構函式實作。", "NEWLINE_6061": "新行", "Named_property_0_of_types_1_and_2_are_not_identical_2319": "類型 '{1}' 及 '{2}' 的具名屬性 '{0}' 不一致。", @@ -518,6 +529,7 @@ "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "非抽象類別運算式未實作從類別 '{1}' 繼承而來的抽象成員 '{0}'。", "Not_all_code_paths_return_a_value_7030": "部分程式碼路徑並未傳回值。", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "數值索引類型 '{0}' 不可指派給字串索引類型 '{1}'。", + "Numeric_separators_are_not_allowed_here_6188": "這裡不允許數字分隔符號。", "Object_is_possibly_null_2531": "物件可能為「null」。", "Object_is_possibly_null_or_undefined_2533": "物件可能為「null」或「未定義」。", "Object_is_possibly_undefined_2532": "物件可能為「未定義」。", @@ -584,18 +596,19 @@ "Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035": "匯出類別中公用靜態 setter '{0}' 的參數類型具有或正在使用私用名稱 '{1}'。", "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141": "在 strict 模式中進行剖析,並為每個來源檔案發出 \"use strict\"。", "Pattern_0_can_have_at_most_one_Asterisk_character_5061": "模式 '{0}' 最多只可有一個 '*' 字元。", - "Prefix_0_with_an_underscore_90025": "有底線的前置詞 '{0}'。", + "Prefix_0_with_an_underscore_90025": "具有底線的前置詞 '{0}'", "Print_names_of_files_part_of_the_compilation_6155": "列印編譯時檔案部分的名稱。", "Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。", "Print_the_compiler_s_version_6019": "列印編譯器的版本。", "Print_this_message_6017": "列印這則訊息。", - "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 沒有屬性 '{0}'。", + "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "類型 '{1}' 沒有屬性 '{0}'。您指的是 '{2}' 嗎?", "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "屬性 '{0}' 有衝突的宣告,在類型 '{1}' 中無法存取。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "屬性 '{0}' 沒有初始設定式,且未在建構函式中明確指派。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "因為屬性 '{0}' 的 get 存取子沒有傳回類型註釋,致使該屬性意味著類型 'any'。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "因為屬性 '{0}' 的 set 存取子沒有參數類型註釋,致使該屬性意味著類型 'any'。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "類型 '{1}' 中的屬性 '{0}' 無法指派給基底類型 '{2}' 中的相同屬性。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "不得將類型 '{1}' 的屬性 '{0}' 指派給類型 '{2}'。", "Property_0_is_declared_but_its_value_is_never_read_6138": "屬性 '{0}' 已宣告但從未讀取其值。", "Property_0_is_incompatible_with_index_signature_2530": "屬性 '{0}' 和索引簽章不相容。", @@ -634,7 +647,8 @@ "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "當運算式及宣告包含隱含的 'any' 類型時顯示錯誤。", "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。", "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", - "Remove_declaration_for_Colon_0_90004": "移除 {0} 的宣告。", + "Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告", + "Replace_import_with_0_95015": "以 '{0}' 取代匯入。", "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。", "Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。", "Report_errors_in_js_files_8019": "報告 .js 檔案中的錯誤。", @@ -680,7 +694,7 @@ "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052": "匯出類別中公用靜態方法的傳回型別具有或使用私用名稱 '{0}'。", "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184": "因為舊程式中的解決方案並無任何變更,所以會重複使用 '{0}' 中的模組解決方案。", "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183": "對檔案 '{1}' 重複用舊程式中模組 '{0}' 的解決方案。", - "Rewrite_as_the_indexed_access_type_0_90026": "重寫為索引存取類型 '{0}'。", + "Rewrite_as_the_indexed_access_type_0_90026": "重寫為索引存取類型 '{0}'", "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122": "無法判斷根目錄,將略過主要搜尋路徑。", "STRATEGY_6039": "策略", "Scoped_package_detected_looking_in_0_6182": "偵測到範圍套件,正於 '{0}' 尋找", @@ -693,7 +707,7 @@ "Source_Map_Options_6175": "來源對應選項", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "特製化的多載簽章不可指派給任何非特製化的簽章。", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "動態匯入的指定名稱不能是展開元素。", - "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015": "指定 ECMAScript 目標版本: 'ES3' (預設)、'ES5'、'ES2015'、'ES2016'、'ES2017' 或 'ESNEXT'。", + "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015": "指定 ECMAScript 目標版本: 'ES3' (預設)、'ES5'、'ES2015'、'ES2016'、'ES2017'、'ES2018' 或 'ESNEXT'。", "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080": "指定 JSX 程式碼產生: 'preserve'、'react-native' 或 'react'。", "Specify_library_files_to_be_included_in_the_compilation_Colon_6079": "指定編譯內要包含的程式庫檔: ", "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016": "指定模組程式碼產生: 'none'、'commonjs'、'amd'、'system'、'umd'、'es2015' 或 'ESNext'。", @@ -705,6 +719,7 @@ "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定輸入檔案的根目錄。用以控制具有 --outDir 的輸出目錄結構。", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "只有當目標為 ECMAScript 5 及更高版本時,才可使用 'new' 運算式中的擴張運算子。", "Spread_types_may_only_be_created_from_object_types_2698": "Spread 類型只能從物件類型建立。", + "Starting_compilation_in_watch_mode_6031": "在監看模式中開始編譯...", "Statement_expected_1129": "必須是陳述式。", "Statements_are_not_allowed_in_ambient_contexts_1036": "環境內容中不得有陳述式。", "Static_members_cannot_reference_class_type_parameters_2302": "靜態成員不得參考類別類型參數。", @@ -712,8 +727,8 @@ "Strict_Type_Checking_Options_6173": "Strict 類型檢查選項", "String_literal_expected_1141": "必須是字串常值。", "String_literal_with_double_quotes_expected_1327": "應有具雙引號的字串常值。", - "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "使用色彩及內容設計錯誤與訊息的風格 (實驗)。", - "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'.", + "Stylize_errors_and_messages_using_color_and_context_experimental_6073": "使用色彩及內容來設計錯誤與訊息的風格 (實驗)。", + "Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717": "後續的屬性宣告必須具有相同的類型。屬性 '{0}' 的類型必須是 '{1}',但此處卻是類型 '{2}'。", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403": "後續的變數宣告必須具有相同的類型。變數 '{0}' 的類型必須是 '{1}' 但卻是 '{2}'。", "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064": "模式 '{1}' 的替代 '{0}' 類型不正確,必須為 'string',但得到 '{2}'。", "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062": "模式 '{1}' 中的替代 '{0}' 最多只可有一個 '*' 字元。", @@ -797,7 +812,7 @@ "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549": "類型 '{0}' 不是陣列類型或字串類型,或沒有會傳回迭代器的 '[Symbol.iterator]()' 方法。", "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548": "類型 '{0}' 不是陣列類型,或沒有會傳回迭代器的 '[Symbol.iterator]()' 方法。", "Type_0_is_not_assignable_to_type_1_2322": "類型 '{0}' 不可指派給類型 '{1}'。", - "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010": "無法將類型 '{0}' 指派給類型 '{1}'。有兩種使用此名稱的不同類型存在,但彼此並不相關。", + "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719": "無法將類型 '{0}' 指派給類型 '{1}'。有兩種使用此名稱的不同類型存在,但彼此並不相關。", "Type_0_is_not_comparable_to_type_1_2678": "類型 '{0}' 無法和類型 '{1}' 比較。", "Type_0_is_not_generic_2315": "'{0}' 不是泛型類型。", "Type_0_provides_no_match_for_the_signature_1_2658": "類型 '{0}' 沒有符合特徵標記 '{1}' 的項目。", @@ -858,6 +873,7 @@ "Unterminated_template_literal_1160": "未結束的樣板常值。", "Untyped_function_calls_may_not_accept_type_arguments_2347": "不具類型的函式呼叫無法接受類型引數。", "Unused_label_7028": "未使用的標籤。", + "Use_synthetic_default_member_95016": "使用綜合 'default' 成員。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "只有在 ECMAScript 5 及更高版本中,才可在 'for...of' 陳述式中使用字串。", "VERSION_6036": "版本", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "類型為 '{0}' 的值與類型 '{1}' 沒有任何共通的屬性。確定要呼叫嗎?", @@ -909,11 +925,11 @@ "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' 僅能在解構指派內的物件常值屬性中使用。", "case_or_default_expected_1130": "必須是 'case' 或 'default'。", "class_expressions_are_not_currently_supported_9003": "目前不支援 'class' 運算式。", - "const_declarations_can_only_be_declared_inside_a_block_1156": "只可在區塊內宣告 'const' 宣告。", - "const_declarations_must_be_initialized_1155": "'const' 宣告必須初始化 。", + "const_declarations_can_only_be_declared_inside_a_block_1156": "只能在區塊內宣告 'const' 宣告。", + "const_declarations_must_be_initialized_1155": "'const' 宣告必須初始化。", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列舉成員初始設定式已評估為非有限值。", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列舉成員初始設定式已評估為不允許的值 'NaN'。", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列舉只可用於屬性或索引存取運算式中,或者用於匯入宣告或匯出指派的右側 。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列舉只可用於屬性或索引存取運算式中,或用於匯入宣告、匯出指派或類型查詢的右側。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "不得在 strict 模式中對識別碼呼叫 'delete'。", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' 只可用於 .ts 檔案中。", "export_can_only_be_used_in_a_ts_file_8003": "'export=' 只可用於 .ts 檔案中。", diff --git a/package.json b/package.json index fb089b6491811..bef6a200f3953 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "2.7.0", + "version": "2.7.1", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 405fd11f13820..07ceaa135632d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2424,12 +2424,15 @@ namespace ts { const visitedSymbolTables: SymbolTable[] = []; return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols: SymbolTable): Symbol[] | undefined { + /** + * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) + */ + function getAccessibleSymbolChainFromSymbolTable(symbols: SymbolTable, ignoreQualification?: boolean): Symbol[] | undefined { if (!pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - const result = trySymbolTable(symbols); + const result = trySymbolTable(symbols, ignoreQualification); visitedSymbolTables.pop(); return result; } @@ -2441,22 +2444,22 @@ namespace ts { !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); } - function isAccessible(symbolFromSymbolTable: Symbol, resolvedAliasSymbol?: Symbol) { + function isAccessible(symbolFromSymbolTable: Symbol, resolvedAliasSymbol?: Symbol, ignoreQualification?: boolean) { return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible !some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); + (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function isUMDExportSymbol(symbol: Symbol) { return symbol && symbol.declarations && symbol.declarations[0] && isNamespaceExportDeclaration(symbol.declarations[0]); } - function trySymbolTable(symbols: SymbolTable) { + function trySymbolTable(symbols: SymbolTable, ignoreQualification: boolean | undefined) { // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.escapedName))) { + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; } @@ -2469,14 +2472,14 @@ namespace ts { && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration))) { const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; } // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain // but only if the symbolFromSymbolTable can be qualified const candidateTable = getExportsOfSymbol(resolvedImportedSymbol); - const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable); + const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -21028,6 +21031,7 @@ namespace ts { } break; case SyntaxKind.IndexSignature: + case SyntaxKind.SemicolonClassElement: // Can't be private break; default: diff --git a/src/compiler/core.ts b/src/compiler/core.ts index ae506fd616a15..5c89a7bbcdd2a 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -6,7 +6,7 @@ namespace ts { // If changing the text in this section, be sure to test `configureNightly` too. export const versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - export const version = `${versionMajorMinor}.0`; + export const version = `${versionMajorMinor}.1`; } namespace ts { diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index f72876bd5fcb3..50181bb98e4f7 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -801,7 +801,7 @@ namespace ts { } const resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; + const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; const packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; return withPackageId(packageId, resolvedFromFile); } @@ -826,12 +826,13 @@ namespace ts { * * packageDirectory is the directory of the package itself. * subModuleName is the path within the package. - * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "" }. (Part before "/node_modules/" is ignored.) - * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar" }. - * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar" }. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }. + * For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }. */ - function parseNodeModuleFromPath(path: string): { packageDirectory: string, subModuleName: string } | undefined { - path = normalizePath(path); + function parseNodeModuleFromPath(resolved: PathAndExtension): { packageDirectory: string, subModuleName: string } | undefined { + const path = normalizePath(resolved.path); const idx = path.lastIndexOf(nodeModulesPathPart); if (idx === -1) { return undefined; @@ -843,7 +844,7 @@ namespace ts { indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); } const packageDirectory = path.slice(0, indexAfterPackageName); - const subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1)); + const subModuleName = removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + Extension.Dts; return { packageDirectory, subModuleName }; } @@ -852,9 +853,17 @@ namespace ts { return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; } - function removeExtensionAndIndex(path: string): string { - const noExtension = removeFileExtension(path); - return noExtension === "index" ? "" : removeSuffix(noExtension, "/index"); + function addExtensionAndIndex(path: string): string { + if (path === "") { + return "index.d.ts"; + } + if (endsWith(path, ".d.ts")) { + return path; + } + if (endsWith(path, "/index")) { + return path + ".d.ts"; + } + return path + "/index.d.ts"; } /* @internal */ @@ -955,12 +964,31 @@ namespace ts { subModuleName: string, failedLookupLocations: Push, onlyRecordFailures: boolean, - { host, traceEnabled }: ModuleResolutionState, + state: ModuleResolutionState, ): { found: boolean, packageJsonContent: PackageJsonPathFields | undefined, packageId: PackageId | undefined } { + const { host, traceEnabled } = state; const directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); const packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { const packageJsonContent = readJson(packageJsonPath, host); + if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName + const path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + if (typeof path === "string") { + subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + } + else { + const jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); + if (typeof jsPath === "string") { + subModuleName = removeExtension(removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), Extension.Js), Extension.Jsx) + Extension.Dts; + } + else { + subModuleName = "index.d.ts"; + } + } + } + if (!endsWith(subModuleName, Extension.Dts)) { + subModuleName = addExtensionAndIndex(subModuleName); + } const packageId: PackageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName, version: packageJsonContent.version } : undefined; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index bd45857fc51dc..0c9f5765605a2 100755 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2351,9 +2351,30 @@ namespace ts { return false; } - return forEachEmittedFile(getEmitHost(), ({ jsFilePath, declarationFilePath }) => - isSameFile(jsFilePath, file) || - (declarationFilePath && isSameFile(declarationFilePath, file))); + // If this is source file, its not emitted file + const filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + + // If options have --outFile or --out just check that + const out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, removeFileExtension(out) + Extension.Dts); + } + + // If --outDir, check if file is in that directory + if (options.outDir) { + return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + + if (fileExtensionIsOneOf(filePath, supportedJavascriptExtensions) || fileExtensionIs(filePath, Extension.Dts)) { + // Otherwise just check if sourceFile with the name exists + const filePathWithoutExtension = removeFileExtension(filePath); + return !!getSourceFileByPath(combinePaths(filePathWithoutExtension, Extension.Ts) as Path) || + !!getSourceFileByPath(combinePaths(filePathWithoutExtension, Extension.Tsx) as Path); + } + return false; } function isSameFile(file1: string, file2: string) { diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 5d46c8430d2d4..424371ad3117a 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -148,7 +148,7 @@ namespace ts { } function visitLabeledStatement(node: LabeledStatement) { - if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { + if (enclosingFunctionFlags & FunctionFlags.Async) { const statement = unwrapInnermostStatementOfLabel(node); if (statement.kind === SyntaxKind.ForOfStatement && (statement).awaitModifier) { return visitForOfStatement(statement, node); diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index beccb65f7b802..790295c225462 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -68,7 +68,7 @@ namespace ts { const host: ParseConfigFileHost = system; host.onConfigFileDiagnostic = reportDiagnostic; host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(sys, reportDiagnostic, diagnostic); - const result = parseConfigFile(configFileName, optionsToExtend, host); + const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onConfigFileDiagnostic = undefined; host.onUnRecoverableConfigFileDiagnostic = undefined; return result; @@ -77,7 +77,7 @@ namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function parseConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined { + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined { let configFileText: string; try { configFileText = host.readFile(configFileName); @@ -791,7 +791,7 @@ namespace ts { } function parseConfigFile() { - const configParseResult = ts.parseConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); + const configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); rootFileNames = configParseResult.fileNames; compilerOptions = configParseResult.options; configFileSpecs = configParseResult.configFileSpecs; diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index bf5f46de2480c..d27bdf4a38624 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2587,12 +2587,10 @@ Actual: ${stringify(fullActual)}`); actualTextArray.push(text); scriptInfo.updateContent(originalContent); } - const sortedExpectedArray = expectedTextArray.sort(); - const sortedActualArray = actualTextArray.sort(); - if (sortedExpectedArray.length !== sortedActualArray.length) { - this.raiseError(`Expected ${sortedExpectedArray.length} import fixes, got ${sortedActualArray.length}`); + if (expectedTextArray.length !== actualTextArray.length) { + this.raiseError(`Expected ${expectedTextArray.length} import fixes, got ${actualTextArray.length}`); } - ts.zipWith(sortedExpectedArray, sortedActualArray, (expected, actual, index) => { + ts.zipWith(expectedTextArray, actualTextArray, (expected, actual, index) => { if (expected !== actual) { this.raiseError(`Import fix at index ${index} doesn't match.\n${showTextDiff(expected, actual)}`); } diff --git a/src/harness/unittests/extractRanges.ts b/src/harness/unittests/extractRanges.ts index 493c9639c3d08..00fbf334b3877 100644 --- a/src/harness/unittests/extractRanges.ts +++ b/src/harness/unittests/extractRanges.ts @@ -365,6 +365,58 @@ switch (x) { refactor.extractSymbol.Messages.cannotExtractRange.message ]); + testExtractRangeFailed("extractRangeFailed14", + ` + switch(1) { + case [#|1: + break;|] + } + `, + [ + refactor.extractSymbol.Messages.cannotExtractRange.message + ]); + + testExtractRangeFailed("extractRangeFailed15", + ` + switch(1) { + case [#|1: + break|]; + } + `, + [ + refactor.extractSymbol.Messages.cannotExtractRange.message + ]); + + // Documentation only - it would be nice if the result were [$|1|] + testExtractRangeFailed("extractRangeFailed16", + ` + switch(1) { + [#|case 1|]: + break; + } + `, + [ + refactor.extractSymbol.Messages.cannotExtractRange.message + ]); + + // Documentation only - it would be nice if the result were [$|1|] + testExtractRangeFailed("extractRangeFailed17", + ` + switch(1) { + [#|case 1:|] + break; + } + `, + [ + refactor.extractSymbol.Messages.cannotExtractRange.message + ]); + + testExtractRangeFailed("extractRangeFailed18", + `[#|{ 1;|] }`, + [ + refactor.extractSymbol.Messages.cannotExtractRange.message + ]); + testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [refactor.extractSymbol.Messages.cannotExtractIdentifier.message]); }); } \ No newline at end of file diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index af69e35ec18db..fee21fcdb2dc8 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -2846,6 +2846,45 @@ namespace ts.projectSystem { const options = project.getCompilerOptions(); assert.equal(options.outDir, "C:/a/b", ""); }); + + it("dynamic file without external project", () => { + const file: FileOrFolder = { + path: "^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js", + content: "var x = 10;" + }; + const host = createServerHost([libFile], { useCaseSensitiveFileNames: true }); + const projectService = createProjectService(host); + projectService.setCompilerOptionsForInferredProjects({ + module: ModuleKind.CommonJS, + allowJs: true, + allowSyntheticDefaultImports: true, + allowNonTsExtensions: true + }); + projectService.openClientFile(file.path, "var x = 10;"); + + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + const project = projectService.inferredProjects[0]; + checkProjectRootFiles(project, [file.path]); + checkProjectActualFiles(project, [file.path, libFile.path]); + + assert.strictEqual(projectService.getDefaultProjectForFile(server.toNormalizedPath(file.path), /*ensureProject*/ true), project); + const indexOfX = file.content.indexOf("x"); + assert.deepEqual(project.getLanguageService(/*ensureSynchronized*/ true).getQuickInfoAtPosition(file.path, indexOfX), { + kind: ScriptElementKind.variableElement, + kindModifiers: "", + textSpan: { start: indexOfX, length: 1 }, + displayParts: [ + { text: "var", kind: "keyword" }, + { text: " ", kind: "space" }, + { text: "x", kind: "localName" }, + { text: ":", kind: "punctuation" }, + { text: " ", kind: "space" }, + { text: "number", kind: "keyword" } + ], + documentation: [], + tags: [] + }); + }); }); describe("tsserverProjectSystem Proper errors", () => { diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 951d34377a6d0..b9f178c998adb 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -14875,7 +14875,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: BufferSource, status: MediaKeyStatus): void; + (keyId: any, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 1b0ce074f001d..62c777d9c7699 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -1873,7 +1873,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: BufferSource, status: MediaKeyStatus): void; + (keyId: any, status: MediaKeyStatus): void; } interface FunctionStringCallback { (data: string): void; diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 575e00c5b0e6c..5d71ff4c2d398 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -898,7 +898,7 @@ namespace ts.server { const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || - this.createInferredProject(getDirectoryPath(info.path)); + this.createInferredProject(info.isDynamic ? this.currentDirectory : getDirectoryPath(info.path)); project.addRoot(info); project.updateGraph(); @@ -1655,7 +1655,7 @@ namespace ts.server { } private getOrCreateInferredProjectForProjectRootPathIfEnabled(info: ScriptInfo, projectRootPath: NormalizedPath | undefined): InferredProject | undefined { - if (!this.useInferredProjectPerProjectRoot) { + if (info.isDynamic || !this.useInferredProjectPerProjectRoot) { return undefined; } diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index dbadf5c88e7ba..6fc4f241f6511 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -196,7 +196,7 @@ namespace ts.server { /*@internal*/ export function isDynamicFileName(fileName: NormalizedPath) { - return getBaseFileName(fileName)[0] === "^"; + return fileName[0] === "^" || getBaseFileName(fileName)[0] === "^"; } export class ScriptInfo { diff --git a/src/server/server.ts b/src/server/server.ts index 8e53c4d51092a..722193829f980 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -33,6 +33,7 @@ namespace ts.server { const os: { homedir?(): string; tmpdir(): string; + platform(): string; } = require("os"); interface NodeSocket { @@ -824,8 +825,9 @@ namespace ts.server { const logger = createLogger(); const sys = ts.sys; + const nodeVersion = getNodeMajorVersion(); // use watchGuard process on Windows when node version is 4 or later - const useWatchGuard = process.platform === "win32" && getNodeMajorVersion() >= 4; + const useWatchGuard = process.platform === "win32" && nodeVersion >= 4; const originalWatchDirectory: ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); const noopWatcher: FileWatcher = { close: noop }; // This is the function that catches the exceptions when watching directory, and yet lets project service continue to function @@ -980,8 +982,9 @@ namespace ts.server { }; logger.info(`Starting TS Server`); - logger.info(`Version: ${versionMajorMinor}`); + logger.info(`Version: ${version}`); logger.info(`Arguments: ${process.argv.join(" ")}`); + logger.info(`Platform: ${os.platform()} NodeVersion: ${nodeVersion} CaseSensitive: ${sys.useCaseSensitiveFileNames}`); const ioSession = new IOSession(options); process.on("uncaughtException", err => { diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 4c536ce3fd271..ac88d98eba5e4 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -390,7 +390,7 @@ namespace ts.codefix { In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". */ const pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - const relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); + const relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; })); // Only return results for the re-export with the shortest possible path (and also give the other path even if that's long.) diff --git a/src/services/completions.ts b/src/services/completions.ts index 80fdf6c280eb5..bce1eadaf26df 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -20,7 +20,8 @@ namespace ts.Completions { None, ClassElementKeywords, // Keywords at class keyword ConstructorParameterKeywords, // Keywords at constructor parameter - FunctionLikeBodyKeywords // Keywords at function like body + FunctionLikeBodyKeywords, // Keywords at function like body + TypeKeywords, } export function getCompletionsAtPosition( @@ -77,7 +78,7 @@ namespace ts.Completions { } function completionInfoFromData(sourceFile: SourceFile, typeChecker: TypeChecker, compilerOptions: CompilerOptions, log: Log, completionData: CompletionData, includeInsertTextCompletions: boolean): CompletionInfo { - const { symbols, completionKind, isNewIdentifierLocation, location, propertyAccessToConvert, keywordFilters, symbolToOriginInfoMap, recommendedCompletion } = completionData; + const { symbols, completionKind, isNewIdentifierLocation, location, propertyAccessToConvert, keywordFilters, symbolToOriginInfoMap, recommendedCompletion, isJsxInitializer } = completionData; if (sourceFile.languageVariant === LanguageVariant.JSX && location && location.parent && isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, @@ -98,7 +99,7 @@ namespace ts.Completions { const entries: CompletionEntry[] = []; if (isSourceFileJavaScript(sourceFile)) { - const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); + const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { @@ -106,7 +107,7 @@ namespace ts.Completions { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location @@ -166,6 +167,7 @@ namespace ts.Completions { origin: SymbolOriginInfo | undefined, recommendedCompletion: Symbol | undefined, propertyAccessToConvert: PropertyAccessExpression | undefined, + isJsxInitializer: boolean, includeInsertTextCompletions: boolean, ): CompletionEntry | undefined { const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); @@ -173,19 +175,27 @@ namespace ts.Completions { return undefined; } const { name, needsConvertPropertyAccess } = info; - if (needsConvertPropertyAccess && !includeInsertTextCompletions) { - return undefined; - } let insertText: string | undefined; let replacementSpan: TextSpan | undefined; - if (kind === CompletionKind.Global && origin && origin.type === "this-type") { - insertText = needsConvertPropertyAccess ? `this["${name}"]` : `this.${name}`; + if (includeInsertTextCompletions) { + if (origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? `this["${name}"]` : `this.${name}`; + } + else if (needsConvertPropertyAccess) { + // TODO: GH#20619 Use configured quote style + insertText = `["${name}"]`; + replacementSpan = createTextSpanFromBounds(findChildOfKind(propertyAccessToConvert!, SyntaxKind.DotToken, sourceFile)!.getStart(sourceFile), propertyAccessToConvert!.name.end); + } + + if (isJsxInitializer) { + if (insertText === undefined) insertText = name; + insertText = `{${insertText}}`; + } } - else if (needsConvertPropertyAccess) { - // TODO: GH#20619 Use configured quote style - insertText = `["${name}"]`; - replacementSpan = createTextSpanFromBounds(findChildOfKind(propertyAccessToConvert!, SyntaxKind.DotToken, sourceFile)!.getStart(sourceFile), propertyAccessToConvert!.name.end); + + if (insertText !== undefined && !includeInsertTextCompletions) { + return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -234,6 +244,7 @@ namespace ts.Completions { kind: CompletionKind, includeInsertTextCompletions?: boolean, propertyAccessToConvert?: PropertyAccessExpression | undefined, + isJsxInitializer?: boolean, recommendedCompletion?: Symbol, symbolToOriginInfoMap?: SymbolOriginInfoMap, ): Map { @@ -245,7 +256,7 @@ namespace ts.Completions { const uniques = createMap(); for (const symbol of symbols) { const origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[getSymbolId(symbol)] : undefined; - const entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions); + const entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); if (!entry) { continue; } @@ -482,6 +493,7 @@ namespace ts.Completions { location: Node; symbolToOriginInfoMap: SymbolOriginInfoMap; previousToken: Node; + readonly isJsxInitializer: boolean; } function getSymbolCompletionFromEntryId( typeChecker: TypeChecker, @@ -500,7 +512,7 @@ namespace ts.Completions { return { type: "request", request: completionData }; } - const { symbols, location, completionKind, symbolToOriginInfoMap, previousToken } = completionData; + const { symbols, location, completionKind, symbolToOriginInfoMap, previousToken, isJsxInitializer } = completionData; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the @@ -509,7 +521,7 @@ namespace ts.Completions { return firstDefined(symbols, (symbol): SymbolCompletion => { // TODO: Shouldn't need return type annotation (GH#12632) const origin = symbolToOriginInfoMap[getSymbolId(symbol)]; const info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); - return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol" as "symbol", symbol, location, symbolToOriginInfoMap, previousToken } : undefined; + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol" as "symbol", symbol, location, symbolToOriginInfoMap, previousToken, isJsxInitializer } : undefined; }) || { type: "none" }; } @@ -565,7 +577,7 @@ namespace ts.Completions { } case "none": { // Didn't find a symbol with this name. See if we can find a keyword instead. - if (some(getKeywordCompletions(KeywordCompletionFilters.None), c => c.name === name)) { + if (allKeywordsCompletions().some(c => c.name === name)) { return { name, kind: ScriptElementKind.keyword, @@ -677,11 +689,13 @@ namespace ts.Completions { readonly symbolToOriginInfoMap: SymbolOriginInfoMap; readonly recommendedCompletion: Symbol | undefined; readonly previousToken: Node | undefined; + readonly isJsxInitializer: boolean; } type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag }; const enum CompletionKind { ObjectPropertyDeclaration, + /** Note that sometimes we access completions from global scope, but use "None" instead of this. See isGlobalCompletionScope. */ Global, PropertyAccess, MemberLike, @@ -857,6 +871,7 @@ namespace ts.Completions { let isRightOfDot = false; let isRightOfOpenTag = false; let isStartingCloseTag = false; + let isJsxInitializer = false; let location = getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { @@ -915,6 +930,10 @@ namespace ts.Completions { location = contextToken; } break; + + case SyntaxKind.JsxAttribute: + isJsxInitializer = previousToken.kind === SyntaxKind.EqualsToken; + break; } } } @@ -960,7 +979,7 @@ namespace ts.Completions { log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); const recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); - return { kind: CompletionDataKind.Data, symbols, completionKind, propertyAccessToConvert, isNewIdentifierLocation, location, keywordFilters, symbolToOriginInfoMap, recommendedCompletion, previousToken }; + return { kind: CompletionDataKind.Data, symbols, completionKind, propertyAccessToConvert, isNewIdentifierLocation, location, keywordFilters, symbolToOriginInfoMap, recommendedCompletion, previousToken, isJsxInitializer }; type JSDocTagWithTypeExpression = JSDocParameterTag | JSDocPropertyTag | JSDocReturnTag | JSDocTypeTag | JSDocTypedefTag; @@ -1163,6 +1182,9 @@ namespace ts.Completions { } function filterGlobalCompletion(symbols: Symbol[]): void { + const isTypeCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); + if (isTypeCompletion) keywordFilters = KeywordCompletionFilters.TypeKeywords; + filterMutate(symbols, symbol => { if (!isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -1170,19 +1192,14 @@ namespace ts.Completions { return true; } - // This is an alias, follow what it aliases - if (symbol && symbol.flags & SymbolFlags.Alias) { - symbol = typeChecker.getAliasedSymbol(symbol); - } + symbol = skipAlias(symbol, typeChecker); // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(symbol.flags & SymbolFlags.Namespace); } - if (insideJsDocTagTypeExpression || - (!isContextTokenValueLocation(contextToken) && - (isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + if (isTypeCompletion) { // Its a type, but you can reach it by namespace.type as well return symbolCanBeReferencedAtTypeLocation(symbol); } @@ -1199,7 +1216,7 @@ namespace ts.Completions { contextToken.parent.kind === SyntaxKind.TypeQuery; } - function isContextTokenTypeLocation(contextToken: Node) { + function isContextTokenTypeLocation(contextToken: Node): boolean { if (contextToken) { const parentKind = contextToken.parent.kind; switch (contextToken.kind) { @@ -1217,6 +1234,7 @@ namespace ts.Completions { return parentKind === SyntaxKind.AsExpression; } } + return false; } function symbolCanBeReferencedAtTypeLocation(symbol: Symbol): boolean { @@ -2112,13 +2130,13 @@ namespace ts.Completions { const validIdentiferResult: CompletionEntryDisplayNameForSymbol = { name, needsConvertPropertyAccess: false }; if (isIdentifierText(name, target)) return validIdentiferResult; switch (kind) { - case CompletionKind.None: case CompletionKind.MemberLike: return undefined; case CompletionKind.ObjectPropertyDeclaration: // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case CompletionKind.PropertyAccess: + case CompletionKind.None: case CompletionKind.Global: // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === CharacterCodes.space ? undefined : { name, needsConvertPropertyAccess: true }; @@ -2130,51 +2148,38 @@ namespace ts.Completions { } // A cache of completion entries for keywords, these do not change between sessions - const _keywordCompletions: CompletionEntry[][] = []; - function getKeywordCompletions(keywordFilter: KeywordCompletionFilters): CompletionEntry[] { - const completions = _keywordCompletions[keywordFilter]; - if (completions) { - return completions; + const _keywordCompletions: ReadonlyArray[] = []; + const allKeywordsCompletions: () => ReadonlyArray = ts.memoize(() => { + const res: CompletionEntry[] = []; + for (let i = SyntaxKind.FirstKeyword; i <= SyntaxKind.LastKeyword; i++) { + res.push({ + name: tokenToString(i), + kind: ScriptElementKind.keyword, + kindModifiers: ScriptElementKindModifier.none, + sortText: "0" + }); } - return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); - - type FilterKeywordCompletions = (entryName: string) => boolean; - function generateKeywordCompletions(keywordFilter: KeywordCompletionFilters): CompletionEntry[] { + return res; + }); + function getKeywordCompletions(keywordFilter: KeywordCompletionFilters): ReadonlyArray { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(entry => { + const kind = stringToToken(entry.name); switch (keywordFilter) { case KeywordCompletionFilters.None: - return getAllKeywordCompletions(); + // "undefined" is a global variable, so don't need a keyword completion for it. + return kind !== SyntaxKind.UndefinedKeyword; case KeywordCompletionFilters.ClassElementKeywords: - return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + return isClassMemberCompletionKeyword(kind); case KeywordCompletionFilters.ConstructorParameterKeywords: - return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + return isConstructorParameterCompletionKeyword(kind); case KeywordCompletionFilters.FunctionLikeBodyKeywords: - return getFilteredKeywordCompletions(isFunctionLikeBodyCompletionKeywordText); + return isFunctionLikeBodyCompletionKeyword(kind); + case KeywordCompletionFilters.TypeKeywords: + return isTypeKeyword(kind); default: - Debug.assertNever(keywordFilter); + return Debug.assertNever(keywordFilter); } - } - - function getAllKeywordCompletions() { - const allKeywordsCompletions: CompletionEntry[] = []; - for (let i = SyntaxKind.FirstKeyword; i <= SyntaxKind.LastKeyword; i++) { - // "undefined" is a global variable, so don't need a keyword completion for it. - if (i === SyntaxKind.UndefinedKeyword) continue; - allKeywordsCompletions.push({ - name: tokenToString(i), - kind: ScriptElementKind.keyword, - kindModifiers: ScriptElementKindModifier.none, - sortText: "0" - }); - } - return allKeywordsCompletions; - } - - function getFilteredKeywordCompletions(filterFn: FilterKeywordCompletions) { - return filter( - getKeywordCompletions(KeywordCompletionFilters.None), - entry => filterFn(entry.name) - ); - } + })); } function isClassMemberCompletionKeyword(kind: SyntaxKind) { @@ -2222,15 +2227,12 @@ namespace ts.Completions { case SyntaxKind.AbstractKeyword: case SyntaxKind.GetKeyword: case SyntaxKind.SetKeyword: + case SyntaxKind.UndefinedKeyword: return false; } return true; } - function isFunctionLikeBodyCompletionKeywordText(text: string) { - return isFunctionLikeBodyCompletionKeyword(stringToToken(text)); - } - function isEqualityOperatorKind(kind: ts.SyntaxKind): kind is EqualityOperator { switch (kind) { case ts.SyntaxKind.EqualsEqualsEqualsToken: diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 479c387fc6532..3f79a0755e166 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -235,6 +235,16 @@ namespace ts.refactor.extractSymbol { break; } } + + if (!statements.length) { + // https://github.com/Microsoft/TypeScript/issues/20559 + // Ranges like [|case 1: break;|] will fail to populate `statements` because + // they will never find `start` in `start.parent.statements`. + // Consider: We could support ranges like [|case 1:|] by refining them to just + // the expression. + return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, declarations } }; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 9bb3535952383..c724fa5643da8 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1070,12 +1070,16 @@ namespace ts { export const typeKeywords: ReadonlyArray = [ SyntaxKind.AnyKeyword, SyntaxKind.BooleanKeyword, + SyntaxKind.KeyOfKeyword, SyntaxKind.NeverKeyword, + SyntaxKind.NullKeyword, SyntaxKind.NumberKeyword, SyntaxKind.ObjectKeyword, SyntaxKind.StringKeyword, SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, + SyntaxKind.UndefinedKeyword, + SyntaxKind.UniqueKeyword, ]; export function isTypeKeyword(kind: SyntaxKind): boolean { diff --git a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json index ae3917e931a4c..d592022e2e177 100644 --- a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json +++ b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json @@ -2,7 +2,7 @@ "======== Resolving module 'foo/use' from '/index.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/use' from 'node_modules' folder, target file type 'TypeScript'.", - "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/use@1.2.3'.", + "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/use/index.d.ts@1.2.3'.", "File '/node_modules/foo/use.ts' does not exist.", "File '/node_modules/foo/use.tsx' does not exist.", "File '/node_modules/foo/use.d.ts' exist - use it as a name resolution result.", @@ -26,12 +26,15 @@ "File '/node_modules/foo/index.ts' does not exist.", "File '/node_modules/foo/index.tsx' does not exist.", "File '/node_modules/foo/index.d.ts' exist - use it as a name resolution result.", - "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo@1.2.3'.", + "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/index.d.ts@1.2.3'.", "======== Module name './index' was successfully resolved to '/node_modules/foo/index.d.ts'. ========", "======== Resolving module 'foo' from '/node_modules/a/index.d.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", - "Found 'package.json' at '/node_modules/a/node_modules/foo/package.json'. Package ID is 'foo@1.2.3'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' does not have a 'main' field.", + "Found 'package.json' at '/node_modules/a/node_modules/foo/package.json'. Package ID is 'foo/index.d.ts@1.2.3'.", "File '/node_modules/a/node_modules/foo.ts' does not exist.", "File '/node_modules/a/node_modules/foo.tsx' does not exist.", "File '/node_modules/a/node_modules/foo.d.ts' does not exist.", diff --git a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json index a753e3dfb9a1d..108873d70f900 100644 --- a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json +++ b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json @@ -2,7 +2,7 @@ "======== Resolving module '@foo/bar/use' from '/index.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar/use' from 'node_modules' folder, target file type 'TypeScript'.", - "Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/use@1.2.3'.", + "Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/use/index.d.ts@1.2.3'.", "File '/node_modules/@foo/bar/use.ts' does not exist.", "File '/node_modules/@foo/bar/use.tsx' does not exist.", "File '/node_modules/@foo/bar/use.d.ts' exist - use it as a name resolution result.", @@ -26,12 +26,15 @@ "File '/node_modules/@foo/bar/index.ts' does not exist.", "File '/node_modules/@foo/bar/index.tsx' does not exist.", "File '/node_modules/@foo/bar/index.d.ts' exist - use it as a name resolution result.", - "Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar@1.2.3'.", + "Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/index.d.ts@1.2.3'.", "======== Module name './index' was successfully resolved to '/node_modules/@foo/bar/index.d.ts'. ========", "======== Resolving module '@foo/bar' from '/node_modules/a/index.d.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", - "Found 'package.json' at '/node_modules/a/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar@1.2.3'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' does not have a 'main' field.", + "Found 'package.json' at '/node_modules/a/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/index.d.ts@1.2.3'.", "File '/node_modules/a/node_modules/@foo/bar.ts' does not exist.", "File '/node_modules/a/node_modules/@foo/bar.tsx' does not exist.", "File '/node_modules/a/node_modules/@foo/bar.d.ts' does not exist.", diff --git a/tests/baselines/reference/emitter.forAwait.es2015.js b/tests/baselines/reference/emitter.forAwait.es2015.js index 323d62f0ac863..6b6bdd739fded 100644 --- a/tests/baselines/reference/emitter.forAwait.es2015.js +++ b/tests/baselines/reference/emitter.forAwait.es2015.js @@ -24,6 +24,22 @@ async function* f4() { for await (x of y) { } } +//// [file5.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +//// [file6.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} //// [file1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -161,3 +177,75 @@ function f4() { var e_1, _a; }); } +//// [file5.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator]; + return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); +}; +// https://github.com/Microsoft/TypeScript/issues/21363 +function f5() { + return __awaiter(this, void 0, void 0, function* () { + let y; + try { + outer: for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield y_1.next(), !y_1_1.done;) { + const x = yield y_1_1.value; + continue outer; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield _a.call(y_1); + } + finally { if (e_1) throw e_1.error; } + } + var e_1, _a; + }); +} +//// [file6.js] +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator]; + return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +// https://github.com/Microsoft/TypeScript/issues/21363 +function f6() { + return __asyncGenerator(this, arguments, function* f6_1() { + let y; + try { + outer: for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield __await(y_1.next()), !y_1_1.done;) { + const x = yield __await(y_1_1.value); + continue outer; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield __await(_a.call(y_1)); + } + finally { if (e_1) throw e_1.error; } + } + var e_1, _a; + }); +} diff --git a/tests/baselines/reference/emitter.forAwait.es2015.symbols b/tests/baselines/reference/emitter.forAwait.es2015.symbols index 6c4ed3b10e9a5..bc75908f6016e 100644 --- a/tests/baselines/reference/emitter.forAwait.es2015.symbols +++ b/tests/baselines/reference/emitter.forAwait.es2015.symbols @@ -48,3 +48,33 @@ async function* f4() { >y : Symbol(y, Decl(file4.ts, 1, 15)) } } +=== tests/cases/conformance/emitter/es2015/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : Symbol(f5, Decl(file5.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file5.ts, 3, 27)) +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + continue outer; + } +} +=== tests/cases/conformance/emitter/es2015/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : Symbol(f6, Decl(file6.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file6.ts, 3, 27)) +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + continue outer; + } +} diff --git a/tests/baselines/reference/emitter.forAwait.es2015.types b/tests/baselines/reference/emitter.forAwait.es2015.types index ac7321e43b459..e7d1c77f34652 100644 --- a/tests/baselines/reference/emitter.forAwait.es2015.types +++ b/tests/baselines/reference/emitter.forAwait.es2015.types @@ -48,3 +48,37 @@ async function* f4() { >y : any } } +=== tests/cases/conformance/emitter/es2015/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : () => Promise + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} +=== tests/cases/conformance/emitter/es2015/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : () => AsyncIterableIterator + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} diff --git a/tests/baselines/reference/emitter.forAwait.es2017.js b/tests/baselines/reference/emitter.forAwait.es2017.js index 4b3770f02afdd..8eb2144255894 100644 --- a/tests/baselines/reference/emitter.forAwait.es2017.js +++ b/tests/baselines/reference/emitter.forAwait.es2017.js @@ -24,6 +24,22 @@ async function* f4() { for await (x of y) { } } +//// [file5.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +//// [file6.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} //// [file1.js] var __asyncValues = (this && this.__asyncValues) || function (o) { @@ -141,3 +157,65 @@ function f4() { var e_1, _a; }); } +//// [file5.js] +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator]; + return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); +}; +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y; + try { + outer: for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = await y_1.next(), !y_1_1.done;) { + const x = await y_1_1.value; + continue outer; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) await _a.call(y_1); + } + finally { if (e_1) throw e_1.error; } + } + var e_1, _a; +} +//// [file6.js] +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator]; + return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +// https://github.com/Microsoft/TypeScript/issues/21363 +function f6() { + return __asyncGenerator(this, arguments, function* f6_1() { + let y; + try { + outer: for (var y_1 = __asyncValues(y), y_1_1; y_1_1 = yield __await(y_1.next()), !y_1_1.done;) { + const x = yield __await(y_1_1.value); + continue outer; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (y_1_1 && !y_1_1.done && (_a = y_1.return)) yield __await(_a.call(y_1)); + } + finally { if (e_1) throw e_1.error; } + } + var e_1, _a; + }); +} diff --git a/tests/baselines/reference/emitter.forAwait.es2017.symbols b/tests/baselines/reference/emitter.forAwait.es2017.symbols index a08e31f5553c0..184d26c12662e 100644 --- a/tests/baselines/reference/emitter.forAwait.es2017.symbols +++ b/tests/baselines/reference/emitter.forAwait.es2017.symbols @@ -48,3 +48,33 @@ async function* f4() { >y : Symbol(y, Decl(file4.ts, 1, 15)) } } +=== tests/cases/conformance/emitter/es2017/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : Symbol(f5, Decl(file5.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file5.ts, 3, 27)) +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + continue outer; + } +} +=== tests/cases/conformance/emitter/es2017/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : Symbol(f6, Decl(file6.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file6.ts, 3, 27)) +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + continue outer; + } +} diff --git a/tests/baselines/reference/emitter.forAwait.es2017.types b/tests/baselines/reference/emitter.forAwait.es2017.types index 0d886cca4cc58..f1dffdd280a72 100644 --- a/tests/baselines/reference/emitter.forAwait.es2017.types +++ b/tests/baselines/reference/emitter.forAwait.es2017.types @@ -48,3 +48,37 @@ async function* f4() { >y : any } } +=== tests/cases/conformance/emitter/es2017/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : () => Promise + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} +=== tests/cases/conformance/emitter/es2017/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : () => AsyncIterableIterator + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} diff --git a/tests/baselines/reference/emitter.forAwait.es5.js b/tests/baselines/reference/emitter.forAwait.es5.js index 2b073a3f43a40..b4ea4ddcf5484 100644 --- a/tests/baselines/reference/emitter.forAwait.es5.js +++ b/tests/baselines/reference/emitter.forAwait.es5.js @@ -24,6 +24,22 @@ async function* f4() { for await (x of y) { } } +//// [file5.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +//// [file6.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} //// [file1.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -353,3 +369,169 @@ function f4() { }); }); } +//// [file5.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator]; + return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); +}; +// https://github.com/Microsoft/TypeScript/issues/21363 +function f5() { + return __awaiter(this, void 0, void 0, function () { + var y, y_1, y_1_1, x, e_1_1, e_1, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 6, 7, 12]); + y_1 = __asyncValues(y); + _b.label = 1; + case 1: return [4 /*yield*/, y_1.next()]; + case 2: + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, y_1_1.value]; + case 3: + x = _b.sent(); + return [3 /*break*/, 4]; + case 4: return [3 /*break*/, 1]; + case 5: return [3 /*break*/, 12]; + case 6: + e_1_1 = _b.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 7: + _b.trys.push([7, , 10, 11]); + if (!(y_1_1 && !y_1_1.done && (_a = y_1.return))) return [3 /*break*/, 9]; + return [4 /*yield*/, _a.call(y_1)]; + case 8: + _b.sent(); + _b.label = 9; + case 9: return [3 /*break*/, 11]; + case 10: + if (e_1) throw e_1.error; + return [7 /*endfinally*/]; + case 11: return [7 /*endfinally*/]; + case 12: return [2 /*return*/]; + } + }); + }); +} +//// [file6.js] +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator]; + return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +// https://github.com/Microsoft/TypeScript/issues/21363 +function f6() { + return __asyncGenerator(this, arguments, function f6_1() { + var y, y_1, y_1_1, x, e_1_1, e_1, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 6, 7, 12]); + y_1 = __asyncValues(y); + _b.label = 1; + case 1: return [4 /*yield*/, __await(y_1.next())]; + case 2: + if (!(y_1_1 = _b.sent(), !y_1_1.done)) return [3 /*break*/, 5]; + return [4 /*yield*/, __await(y_1_1.value)]; + case 3: + x = _b.sent(); + return [3 /*break*/, 4]; + case 4: return [3 /*break*/, 1]; + case 5: return [3 /*break*/, 12]; + case 6: + e_1_1 = _b.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 7: + _b.trys.push([7, , 10, 11]); + if (!(y_1_1 && !y_1_1.done && (_a = y_1.return))) return [3 /*break*/, 9]; + return [4 /*yield*/, __await(_a.call(y_1))]; + case 8: + _b.sent(); + _b.label = 9; + case 9: return [3 /*break*/, 11]; + case 10: + if (e_1) throw e_1.error; + return [7 /*endfinally*/]; + case 11: return [7 /*endfinally*/]; + case 12: return [2 /*return*/]; + } + }); + }); +} diff --git a/tests/baselines/reference/emitter.forAwait.es5.symbols b/tests/baselines/reference/emitter.forAwait.es5.symbols index 40c5562453ce6..05fb915c0fcf9 100644 --- a/tests/baselines/reference/emitter.forAwait.es5.symbols +++ b/tests/baselines/reference/emitter.forAwait.es5.symbols @@ -48,3 +48,33 @@ async function* f4() { >y : Symbol(y, Decl(file4.ts, 1, 15)) } } +=== tests/cases/conformance/emitter/es5/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : Symbol(f5, Decl(file5.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file5.ts, 3, 27)) +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + continue outer; + } +} +=== tests/cases/conformance/emitter/es5/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : Symbol(f6, Decl(file6.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file6.ts, 3, 27)) +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + continue outer; + } +} diff --git a/tests/baselines/reference/emitter.forAwait.es5.types b/tests/baselines/reference/emitter.forAwait.es5.types index 8c8f6dec723fb..fe0a49a901675 100644 --- a/tests/baselines/reference/emitter.forAwait.es5.types +++ b/tests/baselines/reference/emitter.forAwait.es5.types @@ -48,3 +48,37 @@ async function* f4() { >y : any } } +=== tests/cases/conformance/emitter/es5/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : () => Promise + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} +=== tests/cases/conformance/emitter/es5/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : () => AsyncIterableIterator + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} diff --git a/tests/baselines/reference/emitter.forAwait.esnext.js b/tests/baselines/reference/emitter.forAwait.esnext.js index 7a6c6837c9a2b..0042ae38fbdfd 100644 --- a/tests/baselines/reference/emitter.forAwait.esnext.js +++ b/tests/baselines/reference/emitter.forAwait.esnext.js @@ -24,6 +24,22 @@ async function* f4() { for await (x of y) { } } +//// [file5.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +//// [file6.ts] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} //// [file1.js] async function f1() { @@ -49,3 +65,19 @@ async function* f4() { for await (x of y) { } } +//// [file5.js] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y; + outer: for await (const x of y) { + continue outer; + } +} +//// [file6.js] +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y; + outer: for await (const x of y) { + continue outer; + } +} diff --git a/tests/baselines/reference/emitter.forAwait.esnext.symbols b/tests/baselines/reference/emitter.forAwait.esnext.symbols index 137ebed08022d..2910738102b9d 100644 --- a/tests/baselines/reference/emitter.forAwait.esnext.symbols +++ b/tests/baselines/reference/emitter.forAwait.esnext.symbols @@ -48,3 +48,33 @@ async function* f4() { >y : Symbol(y, Decl(file4.ts, 1, 15)) } } +=== tests/cases/conformance/emitter/esnext/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : Symbol(f5, Decl(file5.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file5.ts, 3, 27)) +>y : Symbol(y, Decl(file5.ts, 2, 7)) + + continue outer; + } +} +=== tests/cases/conformance/emitter/esnext/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : Symbol(f6, Decl(file6.ts, 0, 0)) + + let y: any; +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + outer: for await (const x of y) { +>x : Symbol(x, Decl(file6.ts, 3, 27)) +>y : Symbol(y, Decl(file6.ts, 2, 7)) + + continue outer; + } +} diff --git a/tests/baselines/reference/emitter.forAwait.esnext.types b/tests/baselines/reference/emitter.forAwait.esnext.types index ae52bd1080de5..6339aeebeffc0 100644 --- a/tests/baselines/reference/emitter.forAwait.esnext.types +++ b/tests/baselines/reference/emitter.forAwait.esnext.types @@ -48,3 +48,37 @@ async function* f4() { >y : any } } +=== tests/cases/conformance/emitter/esnext/forAwait/file5.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { +>f5 : () => Promise + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} +=== tests/cases/conformance/emitter/esnext/forAwait/file6.ts === +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { +>f6 : () => AsyncIterableIterator + + let y: any; +>y : any + + outer: for await (const x of y) { +>outer : any +>x : any +>y : any + + continue outer; +>outer : any + } +} diff --git a/tests/baselines/reference/library-reference-10.trace.json b/tests/baselines/reference/library-reference-10.trace.json index ada939d8129d7..ad34c0b1dc3fe 100644 --- a/tests/baselines/reference/library-reference-10.trace.json +++ b/tests/baselines/reference/library-reference-10.trace.json @@ -1,6 +1,7 @@ [ "======== Resolving type reference directive 'jquery', containing file '/foo/consumer.ts', root directory './types'. ========", "Resolving with primary search path './types'.", + "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "Found 'package.json' at './types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "File 'types/jquery/jquery.d.ts' exist - use it as a name resolution result.", @@ -8,6 +9,7 @@ "======== Type reference directive 'jquery' was successfully resolved to '/foo/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/foo/__inferred type names__.ts', root directory './types'. ========", "Resolving with primary search path './types'.", + "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "Found 'package.json' at './types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "File 'types/jquery/jquery.d.ts' exist - use it as a name resolution result.", diff --git a/tests/baselines/reference/library-reference-11.trace.json b/tests/baselines/reference/library-reference-11.trace.json index ef99bb8912f7e..be260b6bc6e2c 100644 --- a/tests/baselines/reference/library-reference-11.trace.json +++ b/tests/baselines/reference/library-reference-11.trace.json @@ -3,6 +3,7 @@ "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'.", "Directory '/a/b/node_modules' does not exist, skipping all lookups in it.", + "'package.json' has 'typings' field 'jquery.d.ts' that references '/a/node_modules/jquery/jquery.d.ts'.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", "File '/a/node_modules/jquery.d.ts' does not exist.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/a/node_modules/jquery/jquery.d.ts'.", diff --git a/tests/baselines/reference/library-reference-12.trace.json b/tests/baselines/reference/library-reference-12.trace.json index 22b1232d30be2..26361703708dc 100644 --- a/tests/baselines/reference/library-reference-12.trace.json +++ b/tests/baselines/reference/library-reference-12.trace.json @@ -3,6 +3,8 @@ "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'.", "Directory '/a/b/node_modules' does not exist, skipping all lookups in it.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'dist/jquery.d.ts' that references '/a/node_modules/jquery/dist/jquery.d.ts'.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", "File '/a/node_modules/jquery.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", diff --git a/tests/baselines/reference/library-reference-2.trace.json b/tests/baselines/reference/library-reference-2.trace.json index e708d11c4647f..6111a5e78cfe8 100644 --- a/tests/baselines/reference/library-reference-2.trace.json +++ b/tests/baselines/reference/library-reference-2.trace.json @@ -1,6 +1,8 @@ [ "======== Resolving type reference directive 'jquery', containing file '/consumer.ts', root directory '/types'. ========", "Resolving with primary search path '/types'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "Found 'package.json' at '/types/jquery/package.json'.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", @@ -9,6 +11,8 @@ "======== Type reference directive 'jquery' was successfully resolved to '/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file 'test/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "Found 'package.json' at '/types/jquery/package.json'.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", diff --git a/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.js b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.js new file mode 100644 index 0000000000000..77b1b5f8ff430 --- /dev/null +++ b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.js @@ -0,0 +1,60 @@ +//// [tests/cases/compiler/moduleDeclarationExportStarShadowingGlobalIsNameable.ts] //// + +//// [index.ts] +export * from "./account"; + +//// [account.ts] +export interface Account { + myAccNum: number; +} +interface Account2 { + myAccNum: number; +} +export { Account2 as Acc }; + +//// [index.ts] +declare global { + interface Account { + someProp: number; + } + interface Acc { + someProp: number; + } +} +import * as model from "./model"; +export const func = (account: model.Account, acc2: model.Acc) => {}; + + +//// [account.js] +"use strict"; +exports.__esModule = true; +//// [index.js] +"use strict"; +exports.__esModule = true; +//// [index.js] +"use strict"; +exports.__esModule = true; +exports.func = function (account, acc2) { }; + + +//// [account.d.ts] +export interface Account { + myAccNum: number; +} +interface Account2 { + myAccNum: number; +} +export { Account2 as Acc }; +//// [index.d.ts] +export * from "./account"; +//// [index.d.ts] +declare global { + interface Account { + someProp: number; + } + interface Acc { + someProp: number; + } +} +import * as model from "./model"; +export declare const func: (account: model.Account, acc2: model.Acc) => void; diff --git a/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.symbols b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.symbols new file mode 100644 index 0000000000000..add5fce747636 --- /dev/null +++ b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.symbols @@ -0,0 +1,49 @@ +=== tests/cases/compiler/model/index.ts === +export * from "./account"; +No type information for this code. +No type information for this code.=== tests/cases/compiler/model/account.ts === +export interface Account { +>Account : Symbol(Account, Decl(account.ts, 0, 0)) + + myAccNum: number; +>myAccNum : Symbol(Account.myAccNum, Decl(account.ts, 0, 26)) +} +interface Account2 { +>Account2 : Symbol(Account2, Decl(account.ts, 2, 1)) + + myAccNum: number; +>myAccNum : Symbol(Account2.myAccNum, Decl(account.ts, 3, 20)) +} +export { Account2 as Acc }; +>Account2 : Symbol(Acc, Decl(account.ts, 6, 8)) +>Acc : Symbol(Acc, Decl(account.ts, 6, 8)) + +=== tests/cases/compiler/index.ts === +declare global { +>global : Symbol(global, Decl(index.ts, 0, 0)) + + interface Account { +>Account : Symbol(Account, Decl(index.ts, 0, 16)) + + someProp: number; +>someProp : Symbol(Account.someProp, Decl(index.ts, 1, 23)) + } + interface Acc { +>Acc : Symbol(Acc, Decl(index.ts, 3, 5)) + + someProp: number; +>someProp : Symbol(Acc.someProp, Decl(index.ts, 4, 19)) + } +} +import * as model from "./model"; +>model : Symbol(model, Decl(index.ts, 8, 6)) + +export const func = (account: model.Account, acc2: model.Acc) => {}; +>func : Symbol(func, Decl(index.ts, 9, 12)) +>account : Symbol(account, Decl(index.ts, 9, 21)) +>model : Symbol(model, Decl(index.ts, 8, 6)) +>Account : Symbol(model.Account, Decl(account.ts, 0, 0)) +>acc2 : Symbol(acc2, Decl(index.ts, 9, 44)) +>model : Symbol(model, Decl(index.ts, 8, 6)) +>Acc : Symbol(model.Acc, Decl(account.ts, 6, 8)) + diff --git a/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.types b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.types new file mode 100644 index 0000000000000..af27f7e367837 --- /dev/null +++ b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.types @@ -0,0 +1,50 @@ +=== tests/cases/compiler/model/index.ts === +export * from "./account"; +No type information for this code. +No type information for this code.=== tests/cases/compiler/model/account.ts === +export interface Account { +>Account : Account + + myAccNum: number; +>myAccNum : number +} +interface Account2 { +>Account2 : Account2 + + myAccNum: number; +>myAccNum : number +} +export { Account2 as Acc }; +>Account2 : any +>Acc : any + +=== tests/cases/compiler/index.ts === +declare global { +>global : any + + interface Account { +>Account : Account + + someProp: number; +>someProp : number + } + interface Acc { +>Acc : Acc + + someProp: number; +>someProp : number + } +} +import * as model from "./model"; +>model : typeof model + +export const func = (account: model.Account, acc2: model.Acc) => {}; +>func : (account: model.Account, acc2: model.Acc) => void +>(account: model.Account, acc2: model.Acc) => {} : (account: model.Account, acc2: model.Acc) => void +>account : model.Account +>model : any +>Account : model.Account +>acc2 : model.Acc +>model : any +>Acc : model.Acc + diff --git a/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.js b/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.js new file mode 100644 index 0000000000000..88a0f5a10f5ef --- /dev/null +++ b/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.js @@ -0,0 +1,23 @@ +//// [tests/cases/compiler/moduleLocalImportNotIncorrectlyRedirected.ts] //// + +//// [package.json] +{ +"name": "troublesome-lib", +"typings": "lib/index.d.ts", +"version": "0.0.1" +} +//// [index.d.ts] +import { Position } from './utilities/positioning'; +export interface ISpinButton {} +//// [positioning.d.ts] +export * from './positioning/index'; +//// [index.d.ts] +export declare enum Position { + top, +} +//// [index.ts] +import { ISpinButton } from "troublesome-lib"; + +//// [index.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.symbols b/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.symbols new file mode 100644 index 0000000000000..aa2fb0375ed84 --- /dev/null +++ b/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/index.ts === +import { ISpinButton } from "troublesome-lib"; +>ISpinButton : Symbol(ISpinButton, Decl(index.ts, 0, 8)) + +=== tests/cases/compiler/node_modules/troublesome-lib/lib/index.d.ts === +import { Position } from './utilities/positioning'; +>Position : Symbol(Position, Decl(index.d.ts, 0, 8)) + +export interface ISpinButton {} +>ISpinButton : Symbol(ISpinButton, Decl(index.d.ts, 0, 51)) + +=== tests/cases/compiler/node_modules/troublesome-lib/lib/utilities/positioning.d.ts === +export * from './positioning/index'; +No type information for this code.=== tests/cases/compiler/node_modules/troublesome-lib/lib/utilities/positioning/index.d.ts === +export declare enum Position { +>Position : Symbol(Position, Decl(index.d.ts, 0, 0)) + + top, +>top : Symbol(Position.top, Decl(index.d.ts, 0, 30)) +} diff --git a/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.types b/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.types new file mode 100644 index 0000000000000..f3186505cc802 --- /dev/null +++ b/tests/baselines/reference/moduleLocalImportNotIncorrectlyRedirected.types @@ -0,0 +1,20 @@ +=== tests/cases/compiler/index.ts === +import { ISpinButton } from "troublesome-lib"; +>ISpinButton : any + +=== tests/cases/compiler/node_modules/troublesome-lib/lib/index.d.ts === +import { Position } from './utilities/positioning'; +>Position : typeof Position + +export interface ISpinButton {} +>ISpinButton : ISpinButton + +=== tests/cases/compiler/node_modules/troublesome-lib/lib/utilities/positioning.d.ts === +export * from './positioning/index'; +No type information for this code.=== tests/cases/compiler/node_modules/troublesome-lib/lib/utilities/positioning/index.d.ts === +export declare enum Position { +>Position : Position + + top, +>top : Position +} diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json index b619535487bfe..5f32a4bf511ef 100644 --- a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json @@ -2,6 +2,9 @@ "======== Resolving module 'normalize.css' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'normalize.css' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'normalize.css' that references '/node_modules/normalize.css/normalize.css'.", "Found 'package.json' at '/node_modules/normalize.css/package.json'.", "File '/node_modules/normalize.css.ts' does not exist.", "File '/node_modules/normalize.css.tsx' does not exist.", @@ -13,6 +16,9 @@ "File '/node_modules/normalize.css/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'normalize.css' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'normalize.css' that references '/node_modules/normalize.css/normalize.css'.", "Found 'package.json' at '/node_modules/normalize.css/package.json'.", "File '/node_modules/normalize.css.js' does not exist.", "File '/node_modules/normalize.css.jsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json index 50e7fa685a63c..bab6be18d397f 100644 --- a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json @@ -2,6 +2,8 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'foo.js' that references '/node_modules/foo/foo.js'.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.tsx' does not exist.", @@ -24,6 +26,8 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'foo.js' that references '/node_modules/foo/foo.js'.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.js' does not exist.", "File '/node_modules/foo.jsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json index bf5f0b0bbeff6..3473f33c1f258 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json @@ -2,6 +2,8 @@ "======== Resolving module 'foo/bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/foo/bar/types.d.ts'.", "Found 'package.json' at '/node_modules/foo/bar/package.json'.", "File '/node_modules/foo/bar.ts' does not exist.", "File '/node_modules/foo/bar.tsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json index 72d413d0b2c3a..07dc908b74517 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json @@ -2,6 +2,8 @@ "======== Resolving module 'foo/@bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/@bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/foo/@bar/types.d.ts'.", "Found 'package.json' at '/node_modules/foo/@bar/package.json'.", "File '/node_modules/foo/@bar.ts' does not exist.", "File '/node_modules/foo/@bar.tsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json index 69dcfca4eb681..77ea6a244c1a5 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json @@ -2,6 +2,8 @@ "======== Resolving module '@foo/bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/@foo/bar/types.d.ts'.", "Found 'package.json' at '/node_modules/@foo/bar/package.json'.", "File '/node_modules/@foo/bar.ts' does not exist.", "File '/node_modules/@foo/bar.tsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json index e852d58f2b353..453f5c088a308 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json @@ -3,7 +3,7 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", "File '/node_modules/foo/bar/package.json' does not exist.", - "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/bar@1.2.3'.", + "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/bar.ts' does not exist.", "File '/node_modules/foo/bar.tsx' does not exist.", "File '/node_modules/foo/bar.d.ts' does not exist.", @@ -13,7 +13,7 @@ "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo/bar' from 'node_modules' folder, target file type 'JavaScript'.", "File '/node_modules/foo/bar/package.json' does not exist.", - "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/bar@1.2.3'.", + "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/bar.js' does not exist.", "File '/node_modules/foo/bar.jsx' does not exist.", "File '/node_modules/foo/bar/index.js' exist - use it as a name resolution result.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json index 19fe1f125bc3b..b84bac8993a0e 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json @@ -3,7 +3,7 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/@bar' from 'node_modules' folder, target file type 'TypeScript'.", "File '/node_modules/foo/@bar/package.json' does not exist.", - "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/@bar@1.2.3'.", + "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/@bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/@bar.ts' does not exist.", "File '/node_modules/foo/@bar.tsx' does not exist.", "File '/node_modules/foo/@bar.d.ts' does not exist.", @@ -13,7 +13,7 @@ "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo/@bar' from 'node_modules' folder, target file type 'JavaScript'.", "File '/node_modules/foo/@bar/package.json' does not exist.", - "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/@bar@1.2.3'.", + "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/@bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/@bar.js' does not exist.", "File '/node_modules/foo/@bar.jsx' does not exist.", "File '/node_modules/foo/@bar/index.js' exist - use it as a name resolution result.", diff --git a/tests/baselines/reference/packageJsonMain.trace.json b/tests/baselines/reference/packageJsonMain.trace.json index 842f70c3a02d3..6d39b9d4a7b7a 100644 --- a/tests/baselines/reference/packageJsonMain.trace.json +++ b/tests/baselines/reference/packageJsonMain.trace.json @@ -2,6 +2,9 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.tsx' does not exist.", @@ -13,6 +16,9 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.js' does not exist.", "File '/node_modules/foo.jsx' does not exist.", @@ -25,6 +31,9 @@ "======== Resolving module 'bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'rab.js' that references '/node_modules/bar/rab.js'.", "Found 'package.json' at '/node_modules/bar/package.json'.", "File '/node_modules/bar.ts' does not exist.", "File '/node_modules/bar.tsx' does not exist.", @@ -36,6 +45,9 @@ "File '/node_modules/bar/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'bar' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'rab.js' that references '/node_modules/bar/rab.js'.", "Found 'package.json' at '/node_modules/bar/package.json'.", "File '/node_modules/bar.js' does not exist.", "File '/node_modules/bar.jsx' does not exist.", @@ -46,6 +58,9 @@ "======== Resolving module 'baz' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'baz' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'zab' that references '/node_modules/baz/zab'.", "Found 'package.json' at '/node_modules/baz/package.json'.", "File '/node_modules/baz.ts' does not exist.", "File '/node_modules/baz.tsx' does not exist.", @@ -57,6 +72,9 @@ "File '/node_modules/baz/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'baz' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'zab' that references '/node_modules/baz/zab'.", "Found 'package.json' at '/node_modules/baz/package.json'.", "File '/node_modules/baz.js' does not exist.", "File '/node_modules/baz.jsx' does not exist.", diff --git a/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json b/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json index 763c86730ba75..81f5be11a6d76 100644 --- a/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json +++ b/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json @@ -2,6 +2,9 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.tsx' does not exist.", @@ -13,6 +16,9 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' does not have a 'types' field.", + "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.js' does not exist.", "File '/node_modules/foo.jsx' does not exist.", diff --git a/tests/baselines/reference/typingsLookup4.trace.json b/tests/baselines/reference/typingsLookup4.trace.json index 133ea49c22a21..6cd025d099afd 100644 --- a/tests/baselines/reference/typingsLookup4.trace.json +++ b/tests/baselines/reference/typingsLookup4.trace.json @@ -5,6 +5,7 @@ "File '/node_modules/jquery.ts' does not exist.", "File '/node_modules/jquery.tsx' does not exist.", "File '/node_modules/jquery.d.ts' does not exist.", + "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "File '/node_modules/@types/jquery.d.ts' does not exist.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", @@ -17,6 +18,7 @@ "File '/node_modules/kquery.ts' does not exist.", "File '/node_modules/kquery.tsx' does not exist.", "File '/node_modules/kquery.d.ts' does not exist.", + "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "File '/node_modules/@types/kquery.d.ts' does not exist.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", @@ -33,6 +35,7 @@ "File '/node_modules/lquery.ts' does not exist.", "File '/node_modules/lquery.tsx' does not exist.", "File '/node_modules/lquery.d.ts' does not exist.", + "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "File '/node_modules/@types/lquery.d.ts' does not exist.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", @@ -47,6 +50,7 @@ "File '/node_modules/mquery.ts' does not exist.", "File '/node_modules/mquery.tsx' does not exist.", "File '/node_modules/mquery.d.ts' does not exist.", + "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", "File '/node_modules/@types/mquery.d.ts' does not exist.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", @@ -61,6 +65,7 @@ "======== Module name 'mquery' was successfully resolved to '/node_modules/@types/mquery/mquery/index.tsx'. ========", "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "File '/node_modules/@types/jquery/jquery.d.ts' exist - use it as a name resolution result.", @@ -68,6 +73,7 @@ "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'kquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "File '/node_modules/@types/kquery/kquery' does not exist.", @@ -79,6 +85,7 @@ "======== Type reference directive 'kquery' was successfully resolved to '/node_modules/@types/kquery/kquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'lquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "File '/node_modules/@types/lquery/lquery' does not exist.", @@ -88,6 +95,7 @@ "======== Type reference directive 'lquery' was successfully resolved to '/node_modules/@types/lquery/lquery.ts', primary: true. ========", "======== Resolving type reference directive 'mquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", "File '/node_modules/@types/mquery/mquery' does not exist.", diff --git a/tests/baselines/reference/unusedSemicolonInClass.js b/tests/baselines/reference/unusedSemicolonInClass.js new file mode 100644 index 0000000000000..c33f799fec439 --- /dev/null +++ b/tests/baselines/reference/unusedSemicolonInClass.js @@ -0,0 +1,13 @@ +//// [unusedSemicolonInClass.ts] +class Unused { + ; +} + + +//// [unusedSemicolonInClass.js] +var Unused = /** @class */ (function () { + function Unused() { + } + ; + return Unused; +}()); diff --git a/tests/baselines/reference/unusedSemicolonInClass.symbols b/tests/baselines/reference/unusedSemicolonInClass.symbols new file mode 100644 index 0000000000000..0e1832d1f3a6b --- /dev/null +++ b/tests/baselines/reference/unusedSemicolonInClass.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/unusedSemicolonInClass.ts === +class Unused { +>Unused : Symbol(Unused, Decl(unusedSemicolonInClass.ts, 0, 0)) + + ; +} + diff --git a/tests/baselines/reference/unusedSemicolonInClass.types b/tests/baselines/reference/unusedSemicolonInClass.types new file mode 100644 index 0000000000000..118259662f4ee --- /dev/null +++ b/tests/baselines/reference/unusedSemicolonInClass.types @@ -0,0 +1,7 @@ +=== tests/cases/compiler/unusedSemicolonInClass.ts === +class Unused { +>Unused : Unused + + ; +} + diff --git a/tests/cases/compiler/moduleDeclarationExportStarShadowingGlobalIsNameable.ts b/tests/cases/compiler/moduleDeclarationExportStarShadowingGlobalIsNameable.ts new file mode 100644 index 0000000000000..9113e6e329b5d --- /dev/null +++ b/tests/cases/compiler/moduleDeclarationExportStarShadowingGlobalIsNameable.ts @@ -0,0 +1,24 @@ +// @declaration: true +// @filename: model/index.ts +export * from "./account"; + +// @filename: model/account.ts +export interface Account { + myAccNum: number; +} +interface Account2 { + myAccNum: number; +} +export { Account2 as Acc }; + +// @filename: index.ts +declare global { + interface Account { + someProp: number; + } + interface Acc { + someProp: number; + } +} +import * as model from "./model"; +export const func = (account: model.Account, acc2: model.Acc) => {}; diff --git a/tests/cases/compiler/moduleLocalImportNotIncorrectlyRedirected.ts b/tests/cases/compiler/moduleLocalImportNotIncorrectlyRedirected.ts new file mode 100644 index 0000000000000..89d967a32cd77 --- /dev/null +++ b/tests/cases/compiler/moduleLocalImportNotIncorrectlyRedirected.ts @@ -0,0 +1,18 @@ +// @noImplicitReferences: true +// @filename: node_modules/troublesome-lib/package.json +{ +"name": "troublesome-lib", +"typings": "lib/index.d.ts", +"version": "0.0.1" +} +// @filename: node_modules/troublesome-lib/lib/index.d.ts +import { Position } from './utilities/positioning'; +export interface ISpinButton {} +// @filename: node_modules/troublesome-lib/lib/utilities/positioning.d.ts +export * from './positioning/index'; +// @filename: node_modules/troublesome-lib/lib/utilities/positioning/index.d.ts +export declare enum Position { + top, +} +// @filename: index.ts +import { ISpinButton } from "troublesome-lib"; \ No newline at end of file diff --git a/tests/cases/compiler/unusedSemicolonInClass.ts b/tests/cases/compiler/unusedSemicolonInClass.ts new file mode 100644 index 0000000000000..5cd62690ba9d7 --- /dev/null +++ b/tests/cases/compiler/unusedSemicolonInClass.ts @@ -0,0 +1,4 @@ +// @noUnusedLocals: true +class Unused { + ; +} diff --git a/tests/cases/conformance/emitter/es2015/forAwait/emitter.forAwait.es2015.ts b/tests/cases/conformance/emitter/es2015/forAwait/emitter.forAwait.es2015.ts index 2069f08af3097..64b44e901e27f 100644 --- a/tests/cases/conformance/emitter/es2015/forAwait/emitter.forAwait.es2015.ts +++ b/tests/cases/conformance/emitter/es2015/forAwait/emitter.forAwait.es2015.ts @@ -23,4 +23,20 @@ async function* f4() { let x: any, y: any; for await (x of y) { } +} +// @filename: file5.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +// @filename: file6.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } } \ No newline at end of file diff --git a/tests/cases/conformance/emitter/es2017/forAwait/emitter.forAwait.es2017.ts b/tests/cases/conformance/emitter/es2017/forAwait/emitter.forAwait.es2017.ts index f2d1f46873de7..f9d9fc3d4d96b 100644 --- a/tests/cases/conformance/emitter/es2017/forAwait/emitter.forAwait.es2017.ts +++ b/tests/cases/conformance/emitter/es2017/forAwait/emitter.forAwait.es2017.ts @@ -23,4 +23,20 @@ async function* f4() { let x: any, y: any; for await (x of y) { } +} +// @filename: file5.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +// @filename: file6.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } } \ No newline at end of file diff --git a/tests/cases/conformance/emitter/es5/forAwait/emitter.forAwait.es5.ts b/tests/cases/conformance/emitter/es5/forAwait/emitter.forAwait.es5.ts index beb9ac9c2ca2a..a441b0da2bdb3 100644 --- a/tests/cases/conformance/emitter/es5/forAwait/emitter.forAwait.es5.ts +++ b/tests/cases/conformance/emitter/es5/forAwait/emitter.forAwait.es5.ts @@ -23,4 +23,20 @@ async function* f4() { let x: any, y: any; for await (x of y) { } +} +// @filename: file5.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +// @filename: file6.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } } \ No newline at end of file diff --git a/tests/cases/conformance/emitter/esnext/forAwait/emitter.forAwait.esnext.ts b/tests/cases/conformance/emitter/esnext/forAwait/emitter.forAwait.esnext.ts index 2f532f55ed5b6..ea1b030599e9d 100644 --- a/tests/cases/conformance/emitter/esnext/forAwait/emitter.forAwait.esnext.ts +++ b/tests/cases/conformance/emitter/esnext/forAwait/emitter.forAwait.esnext.ts @@ -23,4 +23,20 @@ async function* f4() { let x: any, y: any; for await (x of y) { } +} +// @filename: file5.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function f5() { + let y: any; + outer: for await (const x of y) { + continue outer; + } +} +// @filename: file6.ts +// https://github.com/Microsoft/TypeScript/issues/21363 +async function* f6() { + let y: any; + outer: for await (const x of y) { + continue outer; + } } \ No newline at end of file diff --git a/tests/cases/fourslash/completionsImportBaseUrl.ts b/tests/cases/fourslash/completionsImportBaseUrl.ts new file mode 100644 index 0000000000000..e5f5b07b9f4f7 --- /dev/null +++ b/tests/cases/fourslash/completionsImportBaseUrl.ts @@ -0,0 +1,21 @@ +/// + +// @Filename: /tsconfig.json +////{ +//// "compilerOptions": { +//// "baseUrl": "." +//// } +////} + +// @Filename: /src/a.ts +////export const foo = 0; + +// @Filename: /src/b.ts +////fo/**/ + +// Test that it prefers a relative import (see sourceDisplay). +goTo.marker(""); +verify.completionListContains({ name: "foo", source: "/src/a" }, "const foo: 0", "", "const", undefined, /*hasAction*/ true, { + includeExternalModuleExports: true, + sourceDisplay: "./a", +}); diff --git a/tests/cases/fourslash/completionsJsxAttributeInitializer.ts b/tests/cases/fourslash/completionsJsxAttributeInitializer.ts new file mode 100644 index 0000000000000..510e0630de96c --- /dev/null +++ b/tests/cases/fourslash/completionsJsxAttributeInitializer.ts @@ -0,0 +1,23 @@ +/// + +// @Filename: /a.tsx +////function f(this: { p: number; "a b": number }, x: number): void { +////
; +////} + +goTo.marker(); + +verify.completionListContains("x", "(parameter) x: number", "", "parameter", undefined, undefined, { + includeInsertTextCompletions: true, + insertText: "{x}", +}); + +verify.completionListContains("p", "(property) p: number", "", "property", undefined, undefined, { + includeInsertTextCompletions: true, + insertText: "{this.p}", +}); + +verify.completionListContains("a b", '(property) "a b": number', "", "property", undefined, undefined, { + includeInsertTextCompletions: true, + insertText: '{this["a b"]}', +}); diff --git a/tests/cases/fourslash/completionsThisType.ts b/tests/cases/fourslash/completionsThisType.ts index 58325182a22d1..471251d2134d1 100644 --- a/tests/cases/fourslash/completionsThisType.ts +++ b/tests/cases/fourslash/completionsThisType.ts @@ -3,7 +3,7 @@ ////class C { //// "foo bar": number; //// xyz() { -//// /**/ +//// return (/**/) //// } ////} //// @@ -11,7 +11,7 @@ goTo.marker(""); -verify.completionListContains("xyz", "(method) C.xyz(): void", "", "method", undefined, undefined, { +verify.completionListContains("xyz", "(method) C.xyz(): any", "", "method", undefined, undefined, { includeInsertTextCompletions: true, insertText: "this.xyz", }); diff --git a/tests/cases/fourslash/completionsTypeKeywords.ts b/tests/cases/fourslash/completionsTypeKeywords.ts new file mode 100644 index 0000000000000..198d6dddab405 --- /dev/null +++ b/tests/cases/fourslash/completionsTypeKeywords.ts @@ -0,0 +1,7 @@ +/// + +////type T = /**/ + +goTo.marker(); +verify.completionListContains("undefined", "undefined", undefined, "keyword"); +verify.not.completionListContains("await"); diff --git a/tests/cases/fourslash/importNameCodeFixExistingImport2.ts b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts index 1146f24aeae1e..dbf34f4389ed8 100644 --- a/tests/cases/fourslash/importNameCodeFixExistingImport2.ts +++ b/tests/cases/fourslash/importNameCodeFixExistingImport2.ts @@ -9,8 +9,8 @@ verify.importFixAtPosition([ `import * as ns from "./module"; +ns.f1();`, +`import * as ns from "./module"; import { f1 } from "./module"; f1();`, -`import * as ns from "./module"; -ns.f1();`, ]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts index bc852b5c47ce4..fba8875a61002 100644 --- a/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts +++ b/tests/cases/fourslash/importNameCodeFixNewImportBaseUrl0.ts @@ -13,10 +13,10 @@ //// export function f1() { }; verify.importFixAtPosition([ -`import { f1 } from "./a/b"; +`import { f1 } from "b"; f1();`, -`import { f1 } from "b"; +`import { f1 } from "./a/b"; -f1();` +f1();`, ]); diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts index 218ec4fabb724..3fbae01fab043 100644 --- a/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport0.ts @@ -12,9 +12,9 @@ verify.importFixAtPosition([ `import * as ns from "./foo"; -import { foo } from "./foo"; -foo();`, +ns.foo();`, `import * as ns from "./foo"; -ns.foo();`, +import { foo } from "./foo"; +foo();`, ]); diff --git a/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts index 7a3d19e1532d9..11204b3c4d201 100644 --- a/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts +++ b/tests/cases/fourslash/importNameCodeFixOptionalImport1.ts @@ -7,14 +7,14 @@ //// export function foo() {}; // @Filename: a/foo.ts -//// export { foo } from "bar"; +//// export { foo } from "bar"; verify.importFixAtPosition([ -`import { foo } from "./foo"; +`import { foo } from "bar"; foo();`, -`import { foo } from "bar"; +`import { foo } from "./foo"; foo();`, ]);