diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 0b0229483032c..7e56efc6422c1 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "Popisek se tady nepovoluje.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Element popsané řazené kolekce členů se deklaroval jako nepovinný pomocí otazníku za názvem a před dvojtečkou, nikoli za typem.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Element popsané řazené kolekce členů se deklaroval jako zbytek s třemi tečkami (...) před názvem, nikoli před typem.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Mapovaný typ nemůže deklarovat vlastnosti nebo metody.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicializátor členu v deklaraci výčtu nemůže odkazovat na členy deklarované až po výčtu, a to ani členy definované v jiných výčtech.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Třída mixin musí mít konstruktor s jediným parametrem rest typu any[].", "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Třída mixin, která rozšiřuje proměnnou typu obsahující signaturu abstraktního konstruktu, musí být také deklarovaná jako abstract.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Nepovedlo se najít název {0}. Potřebujete nainstalovat definice typů pro Node? Zkuste npm i --save-dev @types/node.", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Nepovedlo se najít název ‚{0}‘. Potřebujete nainstalovat definice typů pro uzel? Zkuste ‚npm i --save-dev @types/node‘ a pak do pole typů v tsconfig přidejte ‚node‘.", "Cannot_find_namespace_0_2503": "Nenašel se obor názvů {0}.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Obor názvů {0} nejde najít. Měli jste na mysli „{1}“?", "Cannot_find_parameter_0_1225": "Nenašel se parametr {0}.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Nenašla se společná cesta podadresářů pro vstupní soubory.", "Cannot_find_type_definition_file_for_0_2688": "Nejde najít soubor definice pro {0}.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Převést seznam přetížení na jednu signaturu", "Convert_parameters_to_destructured_object_95075": "Převést parametry na destrukturovaný objekt", "Convert_require_to_import_95047": "Převést require na import", - "Convert_to_ES6_module_95017": "Převést na modul ES6", + "Convert_to_ES_module_95017": "Převést na modul ES", "Convert_to_a_bigint_numeric_literal_95091": "Převést na číselný literál bigint", "Convert_to_anonymous_function_95123": "Převést na anonymní funkci", "Convert_to_arrow_function_95125": "Převést na funkci šipky", @@ -561,7 +563,7 @@ "Duplicate_property_0_2718": "Duplicitní vlastnost {0}.", "Dynamic_import_cannot_have_type_arguments_1326": "Dynamický import nemůže mít argumenty typu.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specifikátor dynamického importu musí být typu string, ale tady má typ {0}.", - "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323": "Dynamické importy se podporují jen v případě, že příznak --module je nastavený na es2020, esnext, commonjs, amd, system, umd, node12 nebo nodenext.", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Dynamické importy se podporují jen v případě, že příznak --module je nastavený na es2020, es2022, esnext, commonjs, amd, system, umd, node12 nebo nodenext.", "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450": "Dynamické importy můžou jako argumenty přijímat jenom specifikátor modulu a volitelný kontrolní výraz.", "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324": "Dynamické importy podporují pouze druhý argument, pokud je možnost --module nastavena na hodnotu esnext.", "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Každý člen typu sjednocení {0} má signatury konstruktu, ale žádná z těchto signatur není kompatibilní s jinou signaturou.", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Soubor {0} se nenašel.", "File_Management_6245": "Správa souborů", "File_change_detected_Starting_incremental_compilation_6032": "Zjistila se změna souboru. Spouští se přírůstková kompilace...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Soubor je modul CommonJS; může se převést na modul ES6.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Soubor je modul CommonJS; může být převeden na modul ES.", "File_is_default_library_for_target_specified_here_1426": "Soubor je výchozí knihovna pro cíl, který se zadal na tomto místě.", "File_is_entry_point_of_type_library_specified_here_1419": "Soubor je vstupní bod knihovny typů, která se zadala na tomto místě.", "File_is_included_via_import_here_1399": "Soubor se zahrnuje pomocí importu na tomto místě.", @@ -837,6 +839,7 @@ "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.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Typy JSDoc se můžou přesunout na typy TypeScript.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "Importy JSON jsou v importech režimu modulu ES experimentální.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atributy JSX musí mít přiřazený neprázdný výraz.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "Element JSX {0} nemá odpovídající uzavírací značku.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Třída elementu JSX nepodporuje atributy, protože nemá vlastnost {0}.", @@ -1360,7 +1363,7 @@ "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Globální typ JSX.{0} by neměl mít více než jednu vlastnost.", "The_implementation_signature_is_declared_here_2750": "Signatura implementace se deklarovala tady.", "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "Meta-vlastnost import.meta není povolena v souborech, které se sestaví do výstupu CommonJS.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_system_node12__1343": "Metavlastnost import.meta se povoluje jen v případě, že možnost --module je nastavená na es2020, esnext, system, node12 nebo nodenext.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "Metavlastnost import.meta se povoluje jen v případě, že možnost --module je nastavená na es2020, es2022, esnext, system, node12 nebo nodenext.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Odvozený typ {0} se nedá pojmenovat bez odkazu na {1}. Pravděpodobně to nebude přenosné. Vyžaduje se anotace typu.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Odvozený typ {0} se odkazuje na typ s cyklickou strukturou, která se nedá triviálně serializovat. Musí se použít anotace typu.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.", @@ -1459,9 +1462,9 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Tato syntaxe vyžaduje importovanou podpůrnou aplikaci, ale modul {0} se nenašel.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Tato syntaxe vyžaduje importovanou pomocnou rutinu s názvem {1}, která v {0} neexistuje. Zvažte možnost upgradovat verzi {0}.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Tato syntaxe vyžaduje importovanou pomocnou rutinu s názvem {1} a parametry {2}, která není kompatibilní s tou v {0}. Zvažte upgrade verze {0}.", - "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_noden_1378": "Výrazy await nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na esnext, system nebo nodenext a možnost target je nastavená na es2017 nebo vyšší.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378": "Výrazy await nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na es2022, esnext, system nebo nodenext a možnost target je nastavená na es2017 nebo vyšší.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Deklarace nejvyšší úrovně v souborech .d.ts musí začínat modifikátorem declare, nebo export.", - "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_nodenex_1432": "Smyčky for await nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na esnext, system nebo nodenext a možnost target je nastavená na es2017 nebo vyšší.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432": "Smyčky for await nejvyšší úrovně se povolují jen v případě, že možnost module je nastavená na es2022, esnext, system nebo nodenext a možnost target je nastavená na es2017 nebo vyšší.", "Trailing_comma_not_allowed_1009": "Čárka na konci není povolená.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpiluje každý soubor jako samostatný modul (podobné jako ts.transpileModule).", "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Vyzkoušejte deklaraci npm i --save-dev @types/{1}, pokud existuje, nebo přidejte nový soubor deklarací (.d.ts) s deklarací declare module '{0}';.", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "{0} je definované jako přístupový objekt ve třídě {1}, ale v {2} se tady přepisuje jako vlastnost instance.", "_0_is_deprecated_6385": "{0} je zastaralé.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "{0} není platnou metavlastností pro klíčové slovo {1}. Měli jste na mysli {2}?", + "_0_is_not_allowed_as_a_parameter_name_1390": "{0} není povolen jako název parametru.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "{0} se nepovoluje jako název deklarace proměnné.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Na {0} se přímo nebo nepřímo odkazuje ve vlastním základním výrazu.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Na {0} se odkazuje přímo nebo nepřímo v jeho vlastní anotaci typu.", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index d12ac5ebbd5e5..cc24ba4f5ac34 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "Eine Bezeichnung ist hier nicht zulässig.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Ein bezeichnetes Tupelelement wird optional mit einem Fragezeichen nach dem Namen und vor dem Doppelpunkt deklariert, nicht nach dem Typ.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Ein bezeichnetes Tupelelement wird mit \"...\" vor dem Namen und nicht vor dem Typ als \"rest\" deklariert.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Ein zugeordneter Typ darf keine Eigenschaften oder Methoden deklarieren.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Ein Memberinitialisierer in einer Enumerationsdeklaration darf nicht auf Member verweisen, die anschließend deklariert werden (einschließlich Member, die in anderen Enumerationen definiert sind).", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Eine Mixin-Klasse benötigt einen Konstruktor mit einem einzelnen REST-Parameter des Typs \"any[]\".", "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Eine Mixin-Klasse, die aus einer Typvariable mit einer abstrakten Konstruktsignatur erweitert wird, muss auch als \"abstract\" deklariert werden.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für Node installieren? Versuchen Sie es mit \"npm i --save-dev @types/node\".", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Der Name \"{0}\" wurde nicht gefunden. Müssen Sie Typdefinitionen für Node installieren? Versuchen Sie es mit \"npm i --save-dev @types/node\", und fügen Sie dann dem Typenfeld in Ihrer tsconfig-Datei \"node\" hinzu.", "Cannot_find_namespace_0_2503": "Der Namespace \"{0}\" wurde nicht gefunden.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Namespace \"{0}\" wurde nicht gefunden. Meinten Sie \"{1}\"?", "Cannot_find_parameter_0_1225": "Der Parameter \"{0}\" wurde nicht gefunden.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Das gemeinsame Unterverzeichnis für die Eingabedateien wurde nicht gefunden.", "Cannot_find_type_definition_file_for_0_2688": "Die Typdefinitionsdatei für \"{0}\" wurde nicht gefunden.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Überladungsliste in einzelne Signatur konvertieren", "Convert_parameters_to_destructured_object_95075": "Parameter in destrukturiertes Objekt konvertieren", "Convert_require_to_import_95047": "\"require\" in \"import\" konvertieren", - "Convert_to_ES6_module_95017": "In ES6-Modul konvertieren", + "Convert_to_ES_module_95017": "In ES-Modul konvertieren", "Convert_to_a_bigint_numeric_literal_95091": "In numerisches bigint-Literal konvertieren", "Convert_to_anonymous_function_95123": "In anonyme Funktion konvertieren", "Convert_to_arrow_function_95125": "In Pfeilfunktion konvertieren", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Die Datei \"{0}\" wurde nicht gefunden.", "File_Management_6245": "Dateiverwaltung", "File_change_detected_Starting_incremental_compilation_6032": "Es wurde eine Dateiänderung erkannt. Die inkrementelle Kompilierung wird gestartet...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Die Datei ist ein CommonJS-Modul, sie kann in ein ES6-Modul konvertiert werden.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Die Datei ist ein CommonJS-Modul und kann möglicherweise in ein ES-Modul konvertiert werden.", "File_is_default_library_for_target_specified_here_1426": "Die Datei ist die Standardbibliothek für das hier angegebene Ziel.", "File_is_entry_point_of_type_library_specified_here_1419": "Die Datei ist ein Einstiegspunkt der hier angegebenen Typbibliothek.", "File_is_included_via_import_here_1399": "Die Datei wird hier per Import eingeschlossen.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Das JSDoc-Tag \"@typedef\" muss entweder eine Typanmerkung aufweisen, oder die Tags \"@property\" oder \"@member\" müssen darauf folgen.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc-Typen können nur innerhalb von Dokumentationskommentaren verwendet werden.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc-Typen können in TypeScript-Typen verschoben werden.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "JSON-Importe sind experimentell in Importen im ES-Modulmodus.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX-Attributen darf nur ein nicht leeres expression-Objekt zugewiesen werden.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "Das JSX-Element \"{0}\" weist kein entsprechendes schließendes Tag auf.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Die JSX-Elementklasse unterstützt keine Attribute, weil sie keine Eigenschaft \"{0}\" aufweist.", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "\"{0}\" ist als Accessor in der Klasse \"{1}\" definiert, wird aber hier in \"{2}\" als Instanzeigenschaft überschrieben.", "_0_is_deprecated_6385": "\"{0}\" ist veraltet.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" ist keine gültige Metaeigenschaft für das Schlüsselwort \"{1}\". Meinten Sie \"{2}\"?", + "_0_is_not_allowed_as_a_parameter_name_1390": "\"{0}\" ist als Parametername nicht zulässig.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "\"{0}\" ist als Name für Variablendeklarationen nicht zulässig.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Auf \"{0}\" wird direkt oder indirekt im eigenen Basisausdruck verwiesen.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Auf \"{0}\" wird direkt oder indirekt in der eigenen Typanmerkung verwiesen.", diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 44d7d3f7bb0d4..3d11e6e869add 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "No se permite una etiqueta aquí.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Un elemento de tupla etiquetado se declara como opcional con un signo de interrogación después del nombre y antes de los dos puntos, en lugar de después del tipo.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Un elemento de tupla etiquetado se declara como rest con \"...\" delante del nombre, en lugar de delante del tipo.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Un tipo asignado no puede declarar propiedades ni métodos.", "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_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Una clase mixin que se extiende desde una variable de tipo que contiene una signatura de construcción abstracta debe declararse también como \"abstract\".", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para el nodo? Pruebe \"npm i --save-dev @types/node\".", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "No se encuentra el nombre \"{0}\". ¿Necesita instalar definiciones de tipo para el nodo? Pruebe \"npm i --save-dev @types/node\" y, a continuación, agregue \"node\" al campo de tipos del archivo tsconfig.", "Cannot_find_namespace_0_2503": "No se encuentra el espacio de nombres '{0}'.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "No se encuentra el espacio de nombres \"{0}\". ¿Quería decir \"{1}\"?", "Cannot_find_parameter_0_1225": "No se encuentra el parámetro '{0}'.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "No se encuentra la ruta de acceso de subdirectorio común para los archivos de entrada.", "Cannot_find_type_definition_file_for_0_2688": "No se puede encontrar el archivo de definición de tipo para '{0}'.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Convertir lista de sobrecargas en firma única", "Convert_parameters_to_destructured_object_95075": "Convertir los parámetros en un objeto desestructurado", "Convert_require_to_import_95047": "Convertir \"require\" en \"import\"", - "Convert_to_ES6_module_95017": "Convertir en módulo ES6", + "Convert_to_ES_module_95017": "Convertir en módulo ES", "Convert_to_a_bigint_numeric_literal_95091": "Convertir en un literal numérico bigint", "Convert_to_anonymous_function_95123": "Convertir en función anónima", "Convert_to_arrow_function_95125": "Convertir en función de flecha", @@ -561,7 +563,7 @@ "Duplicate_property_0_2718": "Propiedad \"{0}\" duplicada.", "Dynamic_import_cannot_have_type_arguments_1326": "La importación dinámica no puede tener argumentos de tipo.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "El especificador de la importación dinámica debe ser de tipo \"string\", pero aquí tiene el tipo \"{0}\".", - "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323": "Las importaciones dinámicas solo se admiten cuando la marca \"--módulo\" se establece en \"es2020\", \"esnext\", \"commonjs\", \"amd\", \"system\", \"umd\", \"node12\" o \"nodenext\".", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Las importaciones dinámicas solo se admiten cuando la marca \"--módulo\" está establecida en \"es2020\", \"es2022\", \"esnext\", \"commonjs\", \"amd\", \"system\", \"umd\", \"node12\" o \"nodenext\".", "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450": "Las importaciones dinámicas solo pueden aceptar un especificador de módulo y una aserción opcional como argumentos", "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324": "Las importaciones dinámicas solo admiten un segundo argumento cuando la opción “--módulo” está establecida en ”esnext”.", "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Cada miembro del tipo de unión \"{0}\" tiene signaturas de construcción, pero ninguna de ellas es compatible entre sí.", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Archivo '{0}' no encontrado.", "File_Management_6245": "Administración de archivos", "File_change_detected_Starting_incremental_compilation_6032": "Se detectó un cambio de archivo. Iniciando la compilación incremental...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "El archivo es un módulo CommonJS; se puede convertir a un módulo ES6.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "El archivo es un módulo CommonJS; se puede convertir en un módulo ES.", "File_is_default_library_for_target_specified_here_1426": "El archivo es la biblioteca predeterminada para el destino que se especifica aquí.", "File_is_entry_point_of_type_library_specified_here_1419": "El archivo es el punto de entrada de la biblioteca de tipos que se especifica aquí.", "File_is_included_via_import_here_1399": "El archivo se incluye aquí a través de la importación.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La etiqueta \"@typedef\" de JSDoc debe tener una anotación de tipo o ir seguida de las etiquetas \"@property\" o \"@member\".", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Los tipos JSDoc solo se pueden usar en los comentarios de la documentación.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Los tipos de JSDoc pueden moverse a tipos de TypeScript.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "Las importaciones de JSON son experimentales en las importaciones del modo de módulo ES.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "A los atributos JSX se les debe asignar únicamente un elemento \"expression\" que no esté vacío.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "El elemento JSX '{0}' no tiene la etiqueta de cierre correspondiente.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La clase de elemento JSX no admite atributos porque no tiene una propiedad \"{0}\".", @@ -1360,7 +1363,7 @@ "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "El tipo \"JSX.{0}\" global no puede tener más de una propiedad.", "The_implementation_signature_is_declared_here_2750": "La signatura de implementación se declara aquí.", "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "No se permite la metapropiedad \"import.meta\" en archivos que se compilarán en la salida de CommonJS.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_system_node12__1343": "La metapropiedad \"import.meta\" solo se permite cuando la opción \"--módulo\" es \"es2020\", \"esnext\", \"system\", \"node12\" o \"nodenext\".", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "La metapropiedad \"import.meta\" solo se permite cuando la opción \"--módulo\" es \"es2020\", \"es2022\", \"esnext\", \"system\", \"node12\" o \"nodenext\".", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "No se puede asignar un nombre al tipo inferido de \"{0}\" sin una referencia a \"{1}\". Es probable que no sea portable. Se requiere una anotación de tipo.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "El tipo deducido de \"{0}\" hace referencia a un tipo con una estructura cíclica que no se puede serializar trivialmente. Es necesaria una anotación de tipo.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.", @@ -1459,9 +1462,9 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", que no existe en \"{0}\". Considere la posibilidad de actualizar la versión de \"{0}\".", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Esta sintaxis requiere un asistente importado denominado \"{1}\" con parámetros de {2}, que no es compatible con el de \"{0}\". Pruebe a actualizar la versión de \"{0}\".", - "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_noden_1378": "Las expresiones \"await\" de nivel superior solo se permiten cuando la opción \"módulo\" se establece en \"esnext\", \"system\" o \"nodenext\" y la opción \"destino\" se establece en \"es2017\" o superior.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378": "Las expresiones \"await\" de nivel superior solo se permiten cuando la opción \"módulo\" está establecida en \"es2022\", \"esnext\", \"system\" o \"nodenext\", y la opción \"destino\" está establecida en \"es2017\" o superior.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Las declaraciones de nivel superior de los archivos .d.ts deben comenzar con un modificador \"declare\" o \"export\".", - "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_nodenex_1432": "Los bucles \"for await\" de nivel superior solo se permiten cuando la opción \"módulo\" se establece en \"esnext\", \"system\" o \"nodenext\", y la opción \"destino\" se establece en \"es2017\" o superior.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432": "Los bucles \"for await\" de nivel superior solo se permiten cuando la opción \"módulo\" está establecida en \"es2022\", \"esnext\", \"system\" o \"nodenext\", y la opción \"destino\" está establecida en \"es2017\" o superior.", "Trailing_comma_not_allowed_1009": "No se permite la coma final.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Pruebe \"npm i --save-dev @types/{1}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\".", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "\"{0}\" se define como descriptor de acceso en la clase \"{1}\", pero se reemplaza aquí en \"{2}\" como propiedad de instancia.", "_0_is_deprecated_6385": "\"{0}\" está en desuso.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" no es una propiedad Meta válida para la palabra clave \"{1}\". ¿Pretendía usar \"{2}\"?", + "_0_is_not_allowed_as_a_parameter_name_1390": "No se permite “{0}” como nombre de parámetro.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "No se permite \"{0}\" como nombre de declaración de variable.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Se hace referencia a '{0}' directa o indirectamente en su propia expresión base.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Se hace referencia a '{0}' directa o indirectamente en su propia anotación de tipo.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 0f218fd014029..3353e9c91cb1c 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "Étiquette non autorisée ici.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Un élément de tuple étiqueté est déclaré facultatif avec un point d'interrogation après le nom et avant les deux points, plutôt qu'après le type.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Un élément de tuple étiqueté est déclaré en tant que rest avec '...' avant le nom, plutôt qu'avant le type.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Un type mappé ne peut pas déclarer de propriétés ou de méthodes.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un initialiseur de membre dans une déclaration d'enum ne peut pas référencer des membres déclarés après lui, notamment des membres définis dans d'autres enums.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Une classe mixin doit avoir un constructeur avec un paramètre rest unique de type 'any[]'.", "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Une classe mixin qui s'étend à partir d'une variable de type contenant une signature de construction abstraite doit également être déclarée 'abstract'.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour node ? Essayez 'npm i --save-dev @types/node'.", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Le nom '{0}' est introuvable. Devez-vous installer des définitions de type pour node ? Essayez 'npm i --save-dev @types/node', puis ajoutez 'node' au champ types de votre fichier tsconfig.", "Cannot_find_namespace_0_2503": "L'espace de noms '{0}' est introuvable.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Impossible de trouver l'espace de noms '{0}'. Vouliez-vous dire '{1}'?", "Cannot_find_parameter_0_1225": "Paramètre '{0}' introuvable.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Impossible de trouver le chemin d'accès au sous-répertoire commun pour les fichiers d'entrée.", "Cannot_find_type_definition_file_for_0_2688": "Le fichier de définition de type est introuvable pour '{0}'.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Convertir la liste de surcharge en une seule signature", "Convert_parameters_to_destructured_object_95075": "Convertir les paramètres en objet déstructuré", "Convert_require_to_import_95047": "Convertir 'require' en 'import'", - "Convert_to_ES6_module_95017": "Convertir en module ES6", + "Convert_to_ES_module_95017": "Convertir en module ES", "Convert_to_a_bigint_numeric_literal_95091": "Convertir en littéral numérique bigint", "Convert_to_anonymous_function_95123": "Convertir en fonction anonyme", "Convert_to_arrow_function_95125": "Convertir en fonction arrow", @@ -561,7 +563,7 @@ "Duplicate_property_0_2718": "Propriété dupliquée '{0}'.", "Dynamic_import_cannot_have_type_arguments_1326": "L'importation dynamique ne peut pas avoir d'arguments de type.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Le spécificateur de l'importation dynamique doit être de type 'string', mais ici il est de type '{0}'.", - "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323": "Les importations dynamiques ne sont prises en charge que lorsque l’indicateur « --module » est défini sur « es2020 », « esnext », « commonjs », « amd », « system », « umd », « node12 » ou « nodenext ».", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Les importations dynamiques sont prises en charge uniquement lorsque l’indicateur « --module » est défini sur « es2020 », « es2022 », « esnext », « commonjs », « amd », « system », « umd », « node12 » ou « nodenext ».", "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450": "Les importations dynamiques peuvent accepter uniquement un spécificateur de module et une assertion facultative en tant qu’arguments.", "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324": "Les importations dynamiques prennent uniquement en charge un deuxième argument lorsque l’option « --module » a la valeur « esnext ».", "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Chaque membre du type union '{0}' a des signatures de construction, mais aucune de ces signatures n'est compatible avec les autres.", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Fichier '{0}' introuvable.", "File_Management_6245": "Gestion de fichiers", "File_change_detected_Starting_incremental_compilation_6032": "Modification de fichier détectée. Démarrage de la compilation incrémentielle...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Le fichier est un module CommonJS ; il peut être converti en module ES6.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Le fichier est un module CommonJS ; il peut être converti en module ES.", "File_is_default_library_for_target_specified_here_1426": "Le fichier représente la bibliothèque par défaut de la cible spécifiée ici.", "File_is_entry_point_of_type_library_specified_here_1419": "Le fichier représente le point d'entrée de la bibliothèque de types spécifiée ici.", "File_is_included_via_import_here_1399": "Le fichier est inclus via une importation ici.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "La balise JSDoc '@typedef' doit avoir une annotation de type ou être suivie des balises '@property' ou '@member'.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Les types JSDoc peuvent uniquement être utilisés dans les commentaires de la documentation.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Les types JSDoc peuvent être déplacés vers les types TypeScript.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "Les importations JSON sont expérimentales dans les importations en mode module ES.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Les attributs JSX doivent uniquement être attribués à une 'expression' non vide.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "L'élément JSX '{0}' n'a pas de balise de fermeture correspondante.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe de l'élément JSX ne prend pas en charge les attributs, car elle n'a pas de propriété '{0}'.", @@ -1360,7 +1363,7 @@ "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Le type global 'JSX.{0}' ne peut pas avoir plusieurs propriétés.", "The_implementation_signature_is_declared_here_2750": "La signature d'implémentation est déclarée ici.", "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "La métapropriété « import.meta » n’est pas autorisée dans les fichiers qui seront intégrés dans la sortie CommonJS.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_system_node12__1343": "La métapropriété « import.meta » n'est autorisée que lorsque l'option « --module » est « es2020 », « esnext », « system », « node12 » ou « nodenext ».", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "La méta-propriété « import.meta » est autorisée uniquement lorsque l’option « --module » est « es2020 », « es2022 », « esnext », « system », « node12 » ou « nodenext ».", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Le type déduit de '{0}' ne peut pas être nommé sans référence à '{1}'. Cela n'est probablement pas portable. Une annotation de type est nécessaire.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Le type déduit de '{0}' référence un type avec une structure cyclique qui ne peut pas être sérialisée de manière triviale. Une annotation de type est nécessaire.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Le type déduit de '{0}' référence un type '{1}' inaccessible. Une annotation de type est nécessaire.", @@ -1459,9 +1462,9 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Cette syntaxe nécessite une application d'assistance importée, mais le module '{0}' est introuvable.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Cette syntaxe nécessite une assistance importée nommée '{1}' mais qui n'existe pas dans '{0}'. Effectuez une mise à niveau de votre version de '{0}'.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Cette syntaxe nécessite un composant d'assistance importé nommé '{1}' avec {2} paramètres, ce qui n'est pas compatible avec celui qui se trouve dans '{0}'. Effectuez une mise à niveau de votre version de '{0}'.", - "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_noden_1378": "Les expressions « await » de niveau supérieur ne sont autorisées que lorsque l’option « module » est définie sur « esnext », « system » ou « nodenext » et que l’option « target » est définie sur « es2017 » ou plus.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378": "Les expressions « await » de niveau supérieur sont autorisées uniquement lorsque l’option « module » a la valeur « es2022 », « esnext », « system » ou « nodenext », et que l’option « target » a la valeur « es2017 » ou une valeur supérieure.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Les déclarations de niveau supérieur dans les fichiers .d.ts doivent commencer par un modificateur 'declare' ou 'export'.", - "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_nodenex_1432": "Les boucles « for await » de niveau supérieur ne sont autorisées que lorsque l'option « module » est définie sur « esnext », « system » ou « nodenext » et que l’option « target » est définie sur « es2017 » ou plus.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432": "Les boucles « for await » de niveau supérieur sont autorisées uniquement lorsque l’option « module » a la valeur « es2022 », « esnext », « system » ou « nodenext », et que l’option « target » est définie sur « es2017 » ou une version ultérieure.", "Trailing_comma_not_allowed_1009": "Virgule de fin non autorisée.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilez chaque fichier sous forme de module distinct (semblable à 'ts.transpileModule').", "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Essayez 'npm i --save-dev @types/{1}' s'il existe, ou ajoutez un nouveau fichier de déclaration (.d.ts) contenant 'declare module '{0}';'", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' est défini en tant qu'accesseur dans la classe '{1}', mais il est remplacé ici dans '{2}' en tant que propriété d'instance.", "_0_is_deprecated_6385": "'{0}' est déprécié.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' n'est pas une métapropriété valide pour le mot clé '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' n'est pas autorisé comme nom de paramètre.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' n'est pas autorisé en tant que nom de déclaration de variable.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' est référencé directement ou indirectement dans sa propre expression de base.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' est référencé directement ou indirectement dans sa propre annotation de type.", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index 56935815619b2..495e928a21cb5 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "In questo punto non sono consentite etichette.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Un elemento tupla con etichetta è dichiarato come facoltativo con un punto interrogativo dopo il nome e prima dei due punti, anziché dopo il tipo.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Un elemento tupla con etichetta è dichiarato come inattivo con '...' prima del nome, anziché prima del tipo.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Un tipo di cui è stato eseguito il mapping non può dichiarare proprietà o metodi.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inizializzatore di membro in una dichiarazione di enumerazione non può fare riferimento a membri dichiarati successivamente, inclusi quelli definiti in altre enumerazioni.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una classe mixin deve includere un costruttore con un unico parametro REST di tipo 'any[]'.", "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Una classe mixin estesa da una variabile di tipo contenente una firma del costrutto astratta deve essere dichiarata anche come 'abstract'.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per il nodo? Provare con `npm i --save-dev @types/node`.", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Non è possibile trovare il nome '{0}'. È necessario installare le definizioni di tipo per il nodo? Provare con `npm i --save-dev @types/node` e quindi aggiungere 'node' al campo types in tsconfig.", "Cannot_find_namespace_0_2503": "Lo spazio dei nomi '{0}' non è stato trovato.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Il nome '{0}' non è stato trovato. Intendevi '{1}'?", "Cannot_find_parameter_0_1225": "Il parametro '{0}' non è stato trovato.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Il percorso della sottodirectory comune per i file di input non è stato trovato.", "Cannot_find_type_definition_file_for_0_2688": "Il file di definizione del tipo per '{0}' non è stato trovato.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Convertire l'elenco di overload in una firma singola", "Convert_parameters_to_destructured_object_95075": "Convertire i parametri nell'oggetto destrutturato", "Convert_require_to_import_95047": "Convertire 'require' in 'import'", - "Convert_to_ES6_module_95017": "Convertire nel modulo ES6", + "Convert_to_ES_module_95017": "Converti nel modulo ES6", "Convert_to_a_bigint_numeric_literal_95091": "Convertire in un valore letterale numerico bigint", "Convert_to_anonymous_function_95123": "Convertire nella funzione anonima", "Convert_to_arrow_function_95125": "Convertire nella funzione arrow", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Il file '{0}' non è stato trovato.", "File_Management_6245": "Gestione dei file", "File_change_detected_Starting_incremental_compilation_6032": "È stata rilevata una modifica ai file. Verrà avviata la compilazione incrementale...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Il file è un modulo CommonJS; può essere convertito in un modulo ES6.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Il file è un modulo CommonJS e può essere convertito in un modulo ES6.", "File_is_default_library_for_target_specified_here_1426": "Il file è la libreria predefinita per la destinazione specificata in questo punto.", "File_is_entry_point_of_type_library_specified_here_1419": "Il file è il punto di ingresso della libreria dei tipi specificata in questo punto.", "File_is_included_via_import_here_1399": "Il file viene incluso tramite importazione in questo punto.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Il tag '@typedef' di JSDoc deve contenere un'annotazione di tipo o essere seguito dal tag '@property' o '@member'.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "I tipi JSDoc possono essere usati solo nei commenti della documentazione.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "I tipi JSDoc possono essere convertiti in tipi TypeScript.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "Le importazioni JSON sono sperimentali nelle importazioni in modalità modulo ES.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Agli attributi JSX deve essere assegnato solo un elemento 'expression' non vuoto.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "Per l'elemento JSX '{0}' non esiste alcun tag di chiusura corrispondente.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "La classe dell'elemento JSX non supporta gli attributi perché non contiene una proprietà '{0}'.", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' è definito come funzione di accesso nella classe '{1}', ma in questo punto ne viene eseguito l'override in '{2}' come proprietà di istanza.", "_0_is_deprecated_6385": "'{0}' è deprecato.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' non è una metaproprietà valida per la parola chiave '{1}'. Si intendeva '{2}'?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' non è un nome di parametro consentito.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' non è consentito come nome di una dichiarazione di variabile.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' viene usato come riferimento diretto o indiretto nella relativa espressione di base.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' viene usato come riferimento diretto o indiretto nella relativa annotazione di tipo.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 6389943484646..bcb7f5e3b8730 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "A ラベルはここでは使用できません。", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "ラベル付きのタプル要素を optional として宣言するには、型の後ではなく名前の後とコロンの前に疑問符を付けます。", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "ラベル付きのタプル要素を rest として宣言するには、型の前ではなく名前の前に '...' を付けます。", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "マップされた型では、プロパティまたはメソッドを宣言しない場合があります。", "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_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "抽象コンストラクト シグネチャを含む型変数から拡張される mixin クラスも、'abstract' として宣言する必要があります。", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "名前 '{0}' が見つかりません。ノードの型定義をインストールする必要がありますか? `npm i --save-dev @types/node` をお試しください。", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "名前 '{0}' が見つかりません。ノードの型定義をインストールする必要がありますか? `npm i --save-dev @types/node` を試してから、tsconfig の型フィールドに 'node' を追加してみてください。", "Cannot_find_namespace_0_2503": "名前空間 '{0}' が見つかりません。", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "'{0}' という名前空間は見つかりません。'{1}' ですか?", "Cannot_find_parameter_0_1225": "パラメーター '{0}' が見つかりません。", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "入力ファイルの共通サブディレクトリ パスが見つかりません。", "Cannot_find_type_definition_file_for_0_2688": "'{0}' の型定義ファイルが見つかりません。", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "オーバーロード リストを単一のシグネチャに変換する", "Convert_parameters_to_destructured_object_95075": "パラメーターを非構造化オブジェクトに変換する", "Convert_require_to_import_95047": "'require' を 'import' に変換", - "Convert_to_ES6_module_95017": "ES6 モジュールに変換します", + "Convert_to_ES_module_95017": "ES モジュールに変換する", "Convert_to_a_bigint_numeric_literal_95091": "bigint 数値リテラルに変換する", "Convert_to_anonymous_function_95123": "匿名関数に変換する", "Convert_to_arrow_function_95125": "アロー関数に変換する", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "ファイル '{0}' が見つかりません。", "File_Management_6245": "ファイルの管理", "File_change_detected_Starting_incremental_compilation_6032": "ファイルの変更が検出されました。インクリメンタル コンパイルを開始しています...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "ファイルは CommonJS モジュールです。ES6 モジュールに変換される可能性があります。", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "ファイルは CommonJS モジュールです。ES モジュールに変換される可能性があります。", "File_is_default_library_for_target_specified_here_1426": "ファイルはこちらで指定されたターゲットの既定のライブラリです。", "File_is_entry_point_of_type_library_specified_here_1419": "ファイルはこちらで指定されたタイプ ライブラリのエントリ ポイントです。", "File_is_included_via_import_here_1399": "ファイルはインポートによってこちらに追加されます。", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' タグには、型の注釈を指定するか、後に '@property' タグや '@member' タグを付ける必要があります。", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc の種類は、ドキュメント コメント内でのみ使用できます。", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc の種類は TypeScript の種類に移行される可能性があります。", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "JSON インポートは、ES モジュール モードのインポートでは試験的な機能です。", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 属性は、空ではない '式' にのみ割り当てる必要があります。", "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 要素 '{0}' には対応する終了タグがありません。", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 要素クラスは '{0}' プロパティを含まないため、属性をサポートしません。", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' はクラス '{1}' でアクセサーとして定義されていますが、ここではインスタンス プロパティとして '{2}' でオーバーライドされています。", "_0_is_deprecated_6385": "'{0}' は非推奨です。", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' はキーワード '{1}' に関するメタプロパティとして無効です。候補: '{2}'。", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' はパラメーター名として使用できません。", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' は変数宣言の名前として使用できません。", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' はそれ自身のベース式内で直接または間接的に参照されます。", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' はそれ自身の型の注釈内で直接または間接的に参照されます。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index a5bbcbd05a715..4b3c1b706fc1a 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "여기서는 레이블을 사용할 수 없습니다.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "레이블이 지정된 튜플 요소는 형식 뒤가 아니라 이름 뒤이면서 콜론 앞에 물음표를 사용하여 optional로 선언됩니다.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "레이블이 지정된 튜플 요소는 형식 앞이 아니라 이름 앞에 '...'을 사용하여 rest로 선언됩니다.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "매핑된 형식은 속성 또는 메서드를 선언할 수 없습니다.", "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_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "추상 구문 시그니처를 포함하는 형식 변수에서 확장되는 mixin 클래스는 'abstract'로도 선언되어야 합니다.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "'{0}' 이름을 찾을 수 없습니다. 노드의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/node'를 시도합니다.", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "'{0}' 이름을 찾을 수 없습니다. 노드의 형식 정의를 설치하려는 경우 'npm i --save-dev @types/node'를 시도한 다음, tsconfig의 형식 필드에 'node'를 추가하세요.", "Cannot_find_namespace_0_2503": "'{0}' 네임스페이스를 찾을 수 없습니다.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "네임스페이스 '{0}'을(를) 찾을 수 없습니다. '{1}'을(를) 의미했나요?", "Cannot_find_parameter_0_1225": "'{0}' 매개 변수를 찾을 수 없습니다.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "입력 파일의 공용 하위 디렉터리 경로를 찾을 수 없습니다.", "Cannot_find_type_definition_file_for_0_2688": "'{0}'에 대한 형식 정의 파일을 찾을 수 없습니다.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "오버로드 목록을 단일 시그니처로 변환", "Convert_parameters_to_destructured_object_95075": "매개 변수를 구조 파괴 개체로 변환", "Convert_require_to_import_95047": "'require'를 'import'로 변환", - "Convert_to_ES6_module_95017": "ES6 모듈로 변환", + "Convert_to_ES_module_95017": "ES 모듈로 변환", "Convert_to_a_bigint_numeric_literal_95091": "bigint 숫자 리터럴로 변환", "Convert_to_anonymous_function_95123": "익명 함수로 변환", "Convert_to_arrow_function_95125": "화살표 함수로 변환", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "파일 '{0}'을(를) 찾을 수 없습니다.", "File_Management_6245": "파일 관리", "File_change_detected_Starting_incremental_compilation_6032": "파일 변경이 검색되었습니다. 증분 컴파일을 시작하는 중...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "파일이 CommonJS 모듈입니다. ES6 모듈로 변환될 수 있습니다.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "파일이 CommonJS 모듈입니다. ES 모듈로 변환될 수 있습니다.", "File_is_default_library_for_target_specified_here_1426": "파일은 여기에 지정된 대상의 기본 라이브러리입니다.", "File_is_entry_point_of_type_library_specified_here_1419": "파일은 여기에 지정된 형식 라이브러리의 진입점입니다.", "File_is_included_via_import_here_1399": "파일은 여기에 가져오기를 통해 포함됩니다.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 태그는 형식 주석을 포함하거나, '@property' 또는 '@member' 태그 앞에 와야 합니다.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 유형은 문서 주석 내에서만 사용될 수 있습니다.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 형식이 TypeScript 형식으로 이동될 수 있습니다.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "JSON 가져오기는 ES 모듈 모드 가져오기에서 실험적입니다.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX 특성에는 비어 있지 않은 '식'만 할당할 수 있습니다.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 요소 '{0}'에 닫는 태그가 없습니다.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 요소 클래스는 '{0}' 속성이 없으므로 특성을 지원하지 않습니다.", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}'은(는) '{1}' 클래스의 접근자로 정의되지만, '{2}'에서 인스턴스 속성으로 재정의됩니다.", "_0_is_deprecated_6385": "'{0}'은(는) 사용되지 않습니다.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}'은(는) '{1}' 키워드에 대한 올바른 메타 속성이 아닙니다. '{2}'을(를) 사용하시겠습니까?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}'은(는) 매개 변수 이름으로 사용할 수 없습니다.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}'은(는) 변수 선언 이름으로 사용할 수 없습니다.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}'은(는) 자체 기본 식에서 직간접적으로 참조됩니다.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}'은(는) 자체 형식 주석에서 직간접적으로 참조됩니다.", diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index cb5f1cc05559e..d55a04a94f4fc 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -73,8 +73,8 @@ interface AnimationEventInit extends EventInit { } interface AnimationPlaybackEventInit extends EventInit { - currentTime?: number | null; - timelineTime?: number | null; + currentTime?: CSSNumberish | null; + timelineTime?: CSSNumberish | null; } interface AssignedNodesOptions { @@ -828,6 +828,7 @@ interface MediaTrackCapabilities { interface MediaTrackConstraintSet { aspectRatio?: ConstrainDouble; + autoGainControl?: ConstrainBoolean; channelCount?: ConstrainULong; deviceId?: ConstrainDOMString; echoCancellation?: ConstrainBoolean; @@ -836,6 +837,7 @@ interface MediaTrackConstraintSet { groupId?: ConstrainDOMString; height?: ConstrainULong; latency?: ConstrainDouble; + noiseSuppression?: ConstrainBoolean; sampleRate?: ConstrainULong; sampleSize?: ConstrainULong; suppressLocalAudioPlayback?: ConstrainBoolean; @@ -848,12 +850,14 @@ interface MediaTrackConstraints extends MediaTrackConstraintSet { interface MediaTrackSettings { aspectRatio?: number; + autoGainControl?: boolean; deviceId?: string; echoCancellation?: boolean; facingMode?: string; frameRate?: number; groupId?: string; height?: number; + noiseSuppression?: boolean; restrictOwnAudio?: boolean; sampleRate?: number; sampleSize?: number; @@ -862,12 +866,14 @@ interface MediaTrackSettings { interface MediaTrackSupportedConstraints { aspectRatio?: boolean; + autoGainControl?: boolean; deviceId?: boolean; echoCancellation?: boolean; facingMode?: boolean; frameRate?: boolean; groupId?: boolean; height?: boolean; + noiseSuppression?: boolean; sampleRate?: boolean; sampleSize?: boolean; suppressLocalAudioPlayback?: boolean; @@ -1483,7 +1489,7 @@ interface RequestInit { /** An AbortSignal to set request's signal. */ signal?: AbortSignal | null; /** Can only be null. Used to disassociate request from any Window. */ - window?: any; + window?: null; } interface ResizeObserverOptions { @@ -1887,7 +1893,7 @@ interface AbortSignal extends EventTarget { declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; - // abort(): AbortSignal; + // abort(): AbortSignal; - To be re-added in the future }; interface AbstractRange { @@ -1950,7 +1956,7 @@ interface AnimationEventMap { } interface Animation extends EventTarget { - currentTime: number | null; + currentTime: CSSNumberish | null; effect: AnimationEffect | null; readonly finished: Promise; id: string; @@ -1962,7 +1968,7 @@ interface Animation extends EventTarget { playbackRate: number; readonly ready: Promise; readonly replaceState: AnimationReplaceState; - startTime: number | null; + startTime: CSSNumberish | null; timeline: AnimationTimeline | null; cancel(): void; commitStyles(): void; @@ -2012,8 +2018,8 @@ interface AnimationFrameProvider { } interface AnimationPlaybackEvent extends Event { - readonly currentTime: number | null; - readonly timelineTime: number | null; + readonly currentTime: CSSNumberish | null; + readonly timelineTime: CSSNumberish | null; } declare var AnimationPlaybackEvent: { @@ -2228,6 +2234,7 @@ declare var AudioScheduledSourceNode: { new(): AudioScheduledSourceNode; }; +/** Available only in secure contexts. */ interface AudioWorklet extends Worklet { } @@ -2240,6 +2247,7 @@ interface AudioWorkletNodeEventMap { "processorerror": Event; } +/** Available only in secure contexts. */ interface AudioWorkletNode extends AudioNode { onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null; readonly parameters: AudioParamMap; @@ -2255,6 +2263,7 @@ declare var AudioWorkletNode: { new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode; }; +/** Available only in secure contexts. */ interface AuthenticatorAssertionResponse extends AuthenticatorResponse { readonly authenticatorData: ArrayBuffer; readonly signature: ArrayBuffer; @@ -2266,6 +2275,7 @@ declare var AuthenticatorAssertionResponse: { new(): AuthenticatorAssertionResponse; }; +/** Available only in secure contexts. */ interface AuthenticatorAttestationResponse extends AuthenticatorResponse { readonly attestationObject: ArrayBuffer; } @@ -2275,6 +2285,7 @@ declare var AuthenticatorAttestationResponse: { new(): AuthenticatorAttestationResponse; }; +/** Available only in secure contexts. */ interface AuthenticatorResponse { readonly clientDataJSON: ArrayBuffer; } @@ -2298,6 +2309,7 @@ interface BaseAudioContextEventMap { } interface BaseAudioContext extends EventTarget { + /** Available only in secure contexts. */ readonly audioWorklet: AudioWorklet; readonly currentTime: number; readonly destination: AudioDestinationNode; @@ -2620,6 +2632,7 @@ declare var CSSRuleList: { /** An object that is a CSS declaration block, and exposes style information and various style-related methods and properties. */ interface CSSStyleDeclaration { + accentColor: string; alignContent: string; alignItems: string; alignSelf: string; @@ -2793,11 +2806,14 @@ interface CSSStyleDeclaration { gridAutoRows: string; gridColumn: string; gridColumnEnd: string; + /** @deprecated This is a legacy alias of `columnGap`. */ gridColumnGap: string; gridColumnStart: string; + /** @deprecated This is a legacy alias of `gap`. */ gridGap: string; gridRow: string; gridRowEnd: string; + /** @deprecated This is a legacy alias of `rowGap`. */ gridRowGap: string; gridRowStart: string; gridTemplate: string; @@ -3036,15 +3052,15 @@ interface CSSStyleDeclaration { webkitBorderTopLeftRadius: string; /** @deprecated This is a legacy alias of `borderTopRightRadius`. */ webkitBorderTopRightRadius: string; - /** @deprecated */ + /** @deprecated This is a legacy alias of `boxAlign`. */ webkitBoxAlign: string; - /** @deprecated */ + /** @deprecated This is a legacy alias of `boxFlex`. */ webkitBoxFlex: string; - /** @deprecated */ + /** @deprecated This is a legacy alias of `boxOrdinalGroup`. */ webkitBoxOrdinalGroup: string; - /** @deprecated */ + /** @deprecated This is a legacy alias of `boxOrient`. */ webkitBoxOrient: string; - /** @deprecated */ + /** @deprecated This is a legacy alias of `boxPack`. */ webkitBoxPack: string; /** @deprecated This is a legacy alias of `boxShadow`. */ webkitBoxShadow: string; @@ -3199,7 +3215,10 @@ declare var CSSTransition: { new(): CSSTransition; }; -/** Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. */ +/** + * Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. + * Available only in secure contexts. + */ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; @@ -3215,7 +3234,10 @@ declare var Cache: { new(): Cache; }; -/** The storage for Cache objects. */ +/** + * The storage for Cache objects. + * Available only in secure contexts. + */ interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; @@ -3447,6 +3469,7 @@ interface ChildNode extends Node { interface ClientRect extends DOMRect { } +/** Available only in secure contexts. */ interface Clipboard extends EventTarget { read(): Promise; readText(): Promise; @@ -3550,6 +3573,7 @@ declare var CountQueuingStrategy: { new(init: QueuingStrategyInit): CountQueuingStrategy; }; +/** Available only in secure contexts. */ interface Credential { readonly id: string; readonly type: string; @@ -3560,6 +3584,7 @@ declare var Credential: { new(): Credential; }; +/** Available only in secure contexts. */ interface CredentialsContainer { create(options?: CredentialCreationOptions): Promise; get(options?: CredentialRequestOptions): Promise; @@ -3574,6 +3599,7 @@ declare var CredentialsContainer: { /** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */ interface Crypto { + /** Available only in secure contexts. */ readonly subtle: SubtleCrypto; getRandomValues(array: T): T; } @@ -3583,7 +3609,10 @@ declare var Crypto: { new(): Crypto; }; -/** The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. */ +/** + * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. + * Available only in secure contexts. + */ interface CryptoKey { readonly algorithm: KeyAlgorithm; readonly extractable: boolean; @@ -4091,7 +4120,10 @@ declare var DelayNode: { new(context: BaseAudioContext, options?: DelayOptions): DelayNode; }; -/** The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation. */ +/** + * The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation. + * Available only in secure contexts. + */ interface DeviceMotionEvent extends Event { readonly acceleration: DeviceMotionEventAcceleration | null; readonly accelerationIncludingGravity: DeviceMotionEventAcceleration | null; @@ -4104,19 +4136,24 @@ declare var DeviceMotionEvent: { new(type: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; }; +/** Available only in secure contexts. */ interface DeviceMotionEventAcceleration { readonly x: number | null; readonly y: number | null; readonly z: number | null; } +/** Available only in secure contexts. */ interface DeviceMotionEventRotationRate { readonly alpha: number | null; readonly beta: number | null; readonly gamma: number | null; } -/** The DeviceOrientationEvent provides web developers with information from the physical orientation of the device running the web page. */ +/** + * The DeviceOrientationEvent provides web developers with information from the physical orientation of the device running the web page. + * Available only in secure contexts. + */ interface DeviceOrientationEvent extends Event { readonly absolute: boolean; readonly alpha: number | null; @@ -4414,13 +4451,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad * @param filter A custom NodeFilter function to use. */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter | null): TreeWalker; - /** - * Returns the element for the specified x coordinate and the specified y coordinate. - * @param x The x-offset - * @param y The y-offset - */ - elementFromPoint(x: number, y: number): Element | null; - elementsFromPoint(x: number, y: number): Element[]; /** * Executes a command on the current document, current selection, or the given range. * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. @@ -4578,6 +4608,13 @@ interface DocumentOrShadowRoot { readonly pointerLockElement: Element | null; /** Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. */ readonly styleSheets: StyleSheetList; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element | null; + elementsFromPoint(x: number, y: number): Element[]; getAnimations(): Animation[]; } @@ -4805,6 +4842,16 @@ interface ElementContentEditable { readonly isContentEditable: boolean; } +interface ElementInternals extends ARIAMixin { + /** Returns the ShadowRoot for internals's target element, if the target element is a shadow host, or null otherwise. */ + readonly shadowRoot: ShadowRoot | null; +} + +declare var ElementInternals: { + prototype: ElementInternals; + new(): ElementInternals; +}; + /** Events providing information related to errors in scripts or in files. */ interface ErrorEvent extends Event { readonly colno: number; @@ -5044,13 +5091,10 @@ declare var FileSystemDirectoryEntry: { new(): FileSystemDirectoryEntry; }; -/** @deprecated */ interface FileSystemDirectoryReader { - /** @deprecated */ readEntries(successCallback: FileSystemEntriesCallback, errorCallback?: ErrorCallback): void; } -/** @deprecated */ declare var FileSystemDirectoryReader: { prototype: FileSystemDirectoryReader; new(): FileSystemDirectoryReader; @@ -5187,7 +5231,10 @@ declare var GainNode: { new(context: BaseAudioContext, options?: GainOptions): GainNode; }; -/** This Gamepad API interface defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id. */ +/** + * This Gamepad API interface defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id. + * Available only in secure contexts. + */ interface Gamepad { readonly axes: ReadonlyArray; readonly buttons: ReadonlyArray; @@ -5204,7 +5251,10 @@ declare var Gamepad: { new(): Gamepad; }; -/** An individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device. */ +/** + * An individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device. + * Available only in secure contexts. + */ interface GamepadButton { readonly pressed: boolean; readonly touched: boolean; @@ -5216,7 +5266,10 @@ declare var GamepadButton: { new(): GamepadButton; }; -/** This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to. */ +/** + * This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to. + * Available only in secure contexts. + */ interface GamepadEvent extends Event { readonly gamepad: Gamepad; } @@ -5253,6 +5306,7 @@ declare var Geolocation: { new(): Geolocation; }; +/** Available only in secure contexts. */ interface GeolocationCoordinates { readonly accuracy: number; readonly altitude: number | null; @@ -5268,6 +5322,7 @@ declare var GeolocationCoordinates: { new(): GeolocationCoordinates; }; +/** Available only in secure contexts. */ interface GeolocationPosition { readonly coords: GeolocationCoordinates; readonly timestamp: DOMTimeStamp; @@ -6092,6 +6147,7 @@ interface HTMLElement extends Element, DocumentAndElementEventHandlers, ElementC spellcheck: boolean; title: string; translate: boolean; + attachInternals(): ElementInternals; click(): void; addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -6953,6 +7009,7 @@ interface HTMLMediaElement extends HTMLElement { readonly error: MediaError | null; /** Gets or sets a flag to specify whether playback should restart after it completes. */ loop: boolean; + /** Available only in secure contexts. */ readonly mediaKeys: MediaKeys | null; /** Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. */ muted: boolean; @@ -6990,6 +7047,7 @@ interface HTMLMediaElement extends HTMLElement { pause(): void; /** Loads and starts playback of a media resource. */ play(): Promise; + /** Available only in secure contexts. */ setMediaKeys(mediaKeys: MediaKeys | null): Promise; readonly HAVE_CURRENT_DATA: number; readonly HAVE_ENOUGH_DATA: number; @@ -7543,6 +7601,7 @@ declare var HTMLSelectElement: { interface HTMLSlotElement extends HTMLElement { name: string; + assign(...nodes: (Element | Text)[]): void; assignedElements(options?: AssignedNodesOptions): Element[]; assignedNodes(options?: AssignedNodesOptions): Node[]; addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -8817,7 +8876,10 @@ declare var MediaCapabilities: { new(): MediaCapabilities; }; -/** The MediaDevicesInfo interface contains information that describes a single media input or output device. */ +/** + * The MediaDevicesInfo interface contains information that describes a single media input or output device. + * Available only in secure contexts. + */ interface MediaDeviceInfo { readonly deviceId: string; readonly groupId: string; @@ -8835,7 +8897,10 @@ interface MediaDevicesEventMap { "devicechange": Event; } -/** Provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data. */ +/** + * Provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data. + * Available only in secure contexts. + */ interface MediaDevices extends EventTarget { ondevicechange: ((this: MediaDevices, ev: Event) => any) | null; enumerateDevices(): Promise; @@ -8892,7 +8957,10 @@ declare var MediaError: { readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number; }; -/** This EncryptedMediaExtensions API interface contains the content and related data when the content decryption module generates a message for the session. */ +/** + * This EncryptedMediaExtensions API interface contains the content and related data when the content decryption module generates a message for the session. + * Available only in secure contexts. + */ interface MediaKeyMessageEvent extends Event { readonly message: ArrayBuffer; readonly messageType: MediaKeyMessageType; @@ -8908,7 +8976,10 @@ interface MediaKeySessionEventMap { "message": MediaKeyMessageEvent; } -/** This EncryptedMediaExtensions API interface represents a context for message exchange with a content decryption module (CDM). */ +/** + * This EncryptedMediaExtensions API interface represents a context for message exchange with a content decryption module (CDM). + * Available only in secure contexts. + */ interface MediaKeySession extends EventTarget { readonly closed: Promise; readonly expiration: number; @@ -8932,7 +9003,10 @@ declare var MediaKeySession: { new(): MediaKeySession; }; -/** This EncryptedMediaExtensions API interface is a read-only map of media key statuses by key IDs. */ +/** + * This EncryptedMediaExtensions API interface is a read-only map of media key statuses by key IDs. + * Available only in secure contexts. + */ interface MediaKeyStatusMap { readonly size: number; get(keyId: BufferSource): MediaKeyStatus | undefined; @@ -8945,7 +9019,10 @@ declare var MediaKeyStatusMap: { new(): MediaKeyStatusMap; }; -/** This EncryptedMediaExtensions API interface provides access to a Key System for decryption and/or a content protection provider. You can request an instance of this object using the Navigator.requestMediaKeySystemAccess method. */ +/** + * This EncryptedMediaExtensions API interface provides access to a Key System for decryption and/or a content protection provider. You can request an instance of this object using the Navigator.requestMediaKeySystemAccess method. + * Available only in secure contexts. + */ interface MediaKeySystemAccess { readonly keySystem: string; createMediaKeys(): Promise; @@ -8957,7 +9034,10 @@ declare var MediaKeySystemAccess: { new(): MediaKeySystemAccess; }; -/** This EncryptedMediaExtensions API interface the represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. */ +/** + * This EncryptedMediaExtensions API interface the represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. + * Available only in secure contexts. + */ interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; setServerCertificate(serverCertificate: BufferSource): Promise; @@ -9031,7 +9111,7 @@ declare var MediaQueryListEvent: { interface MediaRecorderEventMap { "dataavailable": BlobEvent; - "error": Event; + "error": MediaRecorderErrorEvent; "pause": Event; "resume": Event; "start": Event; @@ -9042,7 +9122,7 @@ interface MediaRecorder extends EventTarget { readonly audioBitsPerSecond: number; readonly mimeType: string; ondataavailable: ((this: MediaRecorder, ev: BlobEvent) => any) | null; - onerror: ((this: MediaRecorder, ev: Event) => any) | null; + onerror: ((this: MediaRecorder, ev: MediaRecorderErrorEvent) => any) | null; onpause: ((this: MediaRecorder, ev: Event) => any) | null; onresume: ((this: MediaRecorder, ev: Event) => any) | null; onstart: ((this: MediaRecorder, ev: Event) => any) | null; @@ -9461,20 +9541,27 @@ declare var NamedNodeMap: { /** The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. */ interface Navigator extends NavigatorAutomationInformation, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorNetworkInformation, NavigatorOnLine, NavigatorPlugins, NavigatorStorage { + /** Available only in secure contexts. */ readonly clipboard: Clipboard; + /** Available only in secure contexts. */ readonly credentials: CredentialsContainer; readonly doNotTrack: string | null; readonly geolocation: Geolocation; readonly maxTouchPoints: number; readonly mediaCapabilities: MediaCapabilities; + /** Available only in secure contexts. */ readonly mediaDevices: MediaDevices; readonly mediaSession: MediaSession; readonly permissions: Permissions; - readonly pointerEnabled: boolean; + /** Available only in secure contexts. */ readonly serviceWorker: ServiceWorkerContainer; + /** Available only in secure contexts. */ + canShare(data?: ShareData): boolean; getGamepads(): (Gamepad | null)[]; + /** Available only in secure contexts. */ requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise; sendBeacon(url: string | URL, data?: BodyInit | null): boolean; + /** Available only in secure contexts. */ share(data?: ShareData): Promise; vibrate(pattern: VibratePattern): boolean; } @@ -9493,6 +9580,7 @@ interface NavigatorConcurrentHardware { } interface NavigatorContentUtils { + /** Available only in secure contexts. */ registerProtocolHandler(scheme: string, url: string | URL): void; } @@ -9541,6 +9629,7 @@ interface NavigatorPlugins { javaEnabled(): boolean; } +/** Available only in secure contexts. */ interface NavigatorStorage { readonly storage: StorageManager; } @@ -9968,41 +10057,7 @@ declare var Path2D: { new(path?: Path2D | string): Path2D; }; -/** - * This Payment Request API interface is used to store shipping or payment address information. - * @deprecated - */ -interface PaymentAddress { - /** @deprecated */ - readonly addressLine: ReadonlyArray; - /** @deprecated */ - readonly city: string; - /** @deprecated */ - readonly country: string; - /** @deprecated */ - readonly dependentLocality: string; - /** @deprecated */ - readonly organization: string; - /** @deprecated */ - readonly phone: string; - /** @deprecated */ - readonly postalCode: string; - /** @deprecated */ - readonly recipient: string; - /** @deprecated */ - readonly region: string; - /** @deprecated */ - readonly sortingCode: string; - /** @deprecated */ - toJSON(): any; -} - -/** @deprecated */ -declare var PaymentAddress: { - prototype: PaymentAddress; - new(): PaymentAddress; -}; - +/** Available only in secure contexts. */ interface PaymentMethodChangeEvent extends PaymentRequestUpdateEvent { readonly methodDetails: any; readonly methodName: string; @@ -10017,7 +10072,10 @@ interface PaymentRequestEventMap { "paymentmethodchange": Event; } -/** This Payment Request API interface is the primary access point into the API, and lets web content and apps accept payments from the end user. */ +/** + * This Payment Request API interface is the primary access point into the API, and lets web content and apps accept payments from the end user. + * Available only in secure contexts. + */ interface PaymentRequest extends EventTarget { readonly id: string; onpaymentmethodchange: ((this: PaymentRequest, ev: Event) => any) | null; @@ -10035,7 +10093,10 @@ declare var PaymentRequest: { new(methodData: PaymentMethodData[], details: PaymentDetailsInit): PaymentRequest; }; -/** This Payment Request API interface enables a web page to update the details of a PaymentRequest in response to a user action. */ +/** + * This Payment Request API interface enables a web page to update the details of a PaymentRequest in response to a user action. + * Available only in secure contexts. + */ interface PaymentRequestUpdateEvent extends Event { updateWith(detailsPromise: PaymentDetailsUpdate | PromiseLike): void; } @@ -10045,7 +10106,10 @@ declare var PaymentRequestUpdateEvent: { new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; }; -/** This Payment Request API interface is returned after a user selects a payment method and approves a payment request. */ +/** + * This Payment Request API interface is returned after a user selects a payment method and approves a payment request. + * Available only in secure contexts. + */ interface PaymentResponse extends EventTarget { readonly details: any; readonly methodName: string; @@ -10445,6 +10509,7 @@ interface PointerEvent extends MouseEvent { readonly tiltY: number; readonly twist: number; readonly width: number; + /** Available only in secure contexts. */ getCoalescedEvents(): PointerEvent[]; getPredictedEvents(): PointerEvent[]; } @@ -10499,6 +10564,7 @@ declare var PromiseRejectionEvent: { new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent; }; +/** Available only in secure contexts. */ interface PublicKeyCredential extends Credential { readonly rawId: ArrayBuffer; readonly response: AuthenticatorResponse; @@ -10511,7 +10577,10 @@ declare var PublicKeyCredential: { isUserVerifyingPlatformAuthenticatorAvailable(): Promise; }; -/** This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications. */ +/** + * This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications. + * Available only in secure contexts. + */ interface PushManager { getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; @@ -10524,7 +10593,10 @@ declare var PushManager: { readonly supportedContentEncodings: ReadonlyArray; }; -/** This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service. */ +/** + * This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service. + * Available only in secure contexts. + */ interface PushSubscription { readonly endpoint: string; readonly options: PushSubscriptionOptions; @@ -10538,6 +10610,7 @@ declare var PushSubscription: { new(): PushSubscription; }; +/** Available only in secure contexts. */ interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; } @@ -10930,7 +11003,6 @@ interface ReadableStream { pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; tee(): [ReadableStream, ReadableStream]; - forEach(callbackfn: (value: any, key: number, parent: ReadableStream) => void, thisArg?: any): void; } declare var ReadableStream: { @@ -12918,7 +12990,10 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap { "statechange": Event; } -/** This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. */ +/** + * This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. + * Available only in secure contexts. + */ interface ServiceWorker extends EventTarget, AbstractWorker { onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; readonly scriptURL: string; @@ -12942,7 +13017,10 @@ interface ServiceWorkerContainerEventMap { "messageerror": MessageEvent; } -/** The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. */ +/** + * The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. + * Available only in secure contexts. + */ interface ServiceWorkerContainer extends EventTarget { readonly controller: ServiceWorker | null; oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; @@ -12968,7 +13046,10 @@ interface ServiceWorkerRegistrationEventMap { "updatefound": Event; } -/** This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin. */ +/** + * This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin. + * Available only in secure contexts. + */ interface ServiceWorkerRegistration extends EventTarget { readonly active: ServiceWorker | null; readonly installing: ServiceWorker | null; @@ -13286,6 +13367,7 @@ declare var StorageEvent: { new(type: string, eventInitDict?: StorageEventInit): StorageEvent; }; +/** Available only in secure contexts. */ interface StorageManager { estimate(): Promise; persist(): Promise; @@ -13341,7 +13423,10 @@ declare var SubmitEvent: { new(type: string, eventInitDict?: SubmitEventInit): SubmitEvent; }; -/** This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). */ +/** + * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). + * Available only in secure contexts. + */ interface SubtleCrypto { decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; @@ -13368,7 +13453,6 @@ declare var SubtleCrypto: { /** The textual content of Element or Attr. If an element has no markup within its content, it has a single child implementing Text that contains the element's text. However, if the element contains markup, it is parsed into information items and Text nodes that form its children. */ interface Text extends CharacterData, Slottable { - readonly assignedSlot: HTMLSlotElement | null; /** Returns the combined data of all direct Text node siblings. */ readonly wholeText: string; /** Splits data at the given offset and returns the remainder as Text node. */ @@ -16052,7 +16136,9 @@ interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandler readonly menubar: BarProp; name: string; readonly navigator: Navigator; + /** Available only in secure contexts. */ ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; + /** Available only in secure contexts. */ ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; /** @deprecated */ onorientationchange: ((this: Window, ev: Event) => any) | null; @@ -16200,6 +16286,7 @@ interface WindowLocalStorage { } interface WindowOrWorkerGlobalScope { + /** Available only in secure contexts. */ readonly caches: CacheStorage; readonly crossOriginIsolated: boolean; readonly crypto: Crypto; @@ -16248,6 +16335,7 @@ declare var Worker: { new(scriptURL: string | URL, options?: WorkerOptions): Worker; }; +/** Available only in secure contexts. */ interface Worklet { /** * Loads and executes the module script given by moduleURL into all of worklet's global scopes. It can also create additional global scopes as part of this process, depending on the worklet type. The returned promise will fulfill once the script has been successfully loaded and run in all global scopes. @@ -16593,7 +16681,8 @@ declare namespace WebAssembly { var CompileError: { prototype: CompileError; - new(): CompileError; + new(message?: string): CompileError; + (message?: string): CompileError; }; interface Global { @@ -16620,7 +16709,8 @@ declare namespace WebAssembly { var LinkError: { prototype: LinkError; - new(): LinkError; + new(message?: string): LinkError; + (message?: string): LinkError; }; interface Memory { @@ -16649,7 +16739,8 @@ declare namespace WebAssembly { var RuntimeError: { prototype: RuntimeError; - new(): RuntimeError; + new(message?: string): RuntimeError; + (message?: string): RuntimeError; }; interface Table { @@ -16794,7 +16885,7 @@ interface PositionErrorCallback { } interface QueuingStrategySize { - (chunk?: T): number; + (chunk: T): number; } interface RTCPeerConnectionErrorCallback { @@ -17086,7 +17177,9 @@ declare var menubar: BarProp; /** @deprecated */ declare const name: void; declare var navigator: Navigator; +/** Available only in secure contexts. */ declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; +/** Available only in secure contexts. */ declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; /** @deprecated */ declare var onorientationchange: ((this: Window, ev: Event) => any) | null; @@ -17467,6 +17560,7 @@ declare var onstorage: ((this: Window, ev: StorageEvent) => any) | null; declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null; declare var onunload: ((this: Window, ev: Event) => any) | null; declare var localStorage: Storage; +/** Available only in secure contexts. */ declare var caches: CacheStorage; declare var crossOriginIsolated: boolean; declare var crypto: Crypto; @@ -17629,7 +17723,7 @@ type OscillatorType = "custom" | "sawtooth" | "sine" | "square" | "triangle"; type OverSampleType = "2x" | "4x" | "none"; type PanningModelType = "HRTF" | "equalpower"; type PaymentComplete = "fail" | "success" | "unknown"; -type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock"; +type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking"; type PermissionState = "denied" | "granted" | "prompt"; type PlaybackDirection = "alternate" | "alternate-reverse" | "normal" | "reverse"; type PositionAlignSetting = "auto" | "center" | "line-left" | "line-right"; diff --git a/lib/lib.dom.iterable.d.ts b/lib/lib.dom.iterable.d.ts index 26c3966036cd9..761616e2dd668 100644 --- a/lib/lib.dom.iterable.d.ts +++ b/lib/lib.dom.iterable.d.ts @@ -155,6 +155,7 @@ interface NamedNodeMap { } interface Navigator { + /** Available only in secure contexts. */ requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: Iterable): Promise; vibrate(pattern: Iterable): boolean; } @@ -190,13 +191,6 @@ interface PluginArray { interface RTCStatsReport extends ReadonlyMap { } -interface ReadableStream { - [Symbol.iterator](): IterableIterator; - entries(): IterableIterator<[number, any]>; - keys(): IterableIterator; - values(): IterableIterator; -} - interface SVGLengthList { [Symbol.iterator](): IterableIterator; } diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 79c777e2eda33..1f8508ab4c7f9 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -216,13 +216,13 @@ interface ObjectConstructor { /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. + * @param a Object on which to lock the attributes. */ freeze(a: T[]): readonly T[]; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. + * @param f Object on which to lock the attributes. */ freeze(f: T): T; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index d1116d3c15508..242db956ae771 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -497,7 +497,7 @@ interface RequestInit { /** An AbortSignal to set request's signal. */ signal?: AbortSignal | null; /** Can only be null. Used to disassociate request from any Window. */ - window?: any; + window?: null; } interface ResponseInit { @@ -691,7 +691,7 @@ interface AbortSignal extends EventTarget { declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; - // abort(): AbortSignal; + // abort(): AbortSignal; - To be re-added in the future }; interface AbstractWorkerEventMap { @@ -772,7 +772,10 @@ declare var ByteLengthQueuingStrategy: { new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; }; -/** Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. */ +/** + * Provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. + * Available only in secure contexts. + */ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; @@ -788,7 +791,10 @@ declare var Cache: { new(): Cache; }; -/** The storage for Cache objects. */ +/** + * The storage for Cache objects. + * Available only in secure contexts. + */ interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; @@ -896,6 +902,7 @@ declare var CountQueuingStrategy: { /** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */ interface Crypto { + /** Available only in secure contexts. */ readonly subtle: SubtleCrypto; getRandomValues(array: T): T; } @@ -905,7 +912,10 @@ declare var Crypto: { new(): Crypto; }; -/** The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. */ +/** + * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. + * Available only in secure contexts. + */ interface CryptoKey { readonly algorithm: KeyAlgorithm; readonly extractable: boolean; @@ -2157,6 +2167,7 @@ interface NavigatorOnLine { readonly onLine: boolean; } +/** Available only in secure contexts. */ interface NavigatorStorage { readonly storage: StorageManager; } @@ -2451,7 +2462,10 @@ declare var PromiseRejectionEvent: { new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent; }; -/** This Push API interface represents a push message that has been received. This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription. */ +/** + * This Push API interface represents a push message that has been received. This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription. + * Available only in secure contexts. + */ interface PushEvent extends ExtendableEvent { readonly data: PushMessageData | null; } @@ -2461,7 +2475,10 @@ declare var PushEvent: { new(type: string, eventInitDict?: PushEventInit): PushEvent; }; -/** This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications. */ +/** + * This Push API interface provides a way to receive notifications from third-party servers as well as request URLs for push notifications. + * Available only in secure contexts. + */ interface PushManager { getSubscription(): Promise; permissionState(options?: PushSubscriptionOptionsInit): Promise; @@ -2474,7 +2491,10 @@ declare var PushManager: { readonly supportedContentEncodings: ReadonlyArray; }; -/** This Push API interface provides methods which let you retrieve the push data sent by a server in various formats. */ +/** + * This Push API interface provides methods which let you retrieve the push data sent by a server in various formats. + * Available only in secure contexts. + */ interface PushMessageData { arrayBuffer(): ArrayBuffer; blob(): Blob; @@ -2487,7 +2507,10 @@ declare var PushMessageData: { new(): PushMessageData; }; -/** This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service. */ +/** + * This Push API interface provides a subcription's URL endpoint and allows unsubscription from a push service. + * Available only in secure contexts. + */ interface PushSubscription { readonly endpoint: string; readonly options: PushSubscriptionOptions; @@ -2501,6 +2524,7 @@ declare var PushSubscription: { new(): PushSubscription; }; +/** Available only in secure contexts. */ interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; } @@ -2518,7 +2542,6 @@ interface ReadableStream { pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; tee(): [ReadableStream, ReadableStream]; - forEach(callbackfn: (value: any, key: number, parent: ReadableStream) => void, thisArg?: any): void; } declare var ReadableStream: { @@ -2633,7 +2656,10 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap { "statechange": Event; } -/** This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. */ +/** + * This ServiceWorker API interface provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. + * Available only in secure contexts. + */ interface ServiceWorker extends EventTarget, AbstractWorker { onstatechange: ((this: ServiceWorker, ev: Event) => any) | null; readonly scriptURL: string; @@ -2657,7 +2683,10 @@ interface ServiceWorkerContainerEventMap { "messageerror": MessageEvent; } -/** The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. */ +/** + * The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. + * Available only in secure contexts. + */ interface ServiceWorkerContainer extends EventTarget { readonly controller: ServiceWorker | null; oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null; @@ -2718,7 +2747,10 @@ interface ServiceWorkerRegistrationEventMap { "updatefound": Event; } -/** This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin. */ +/** + * This ServiceWorker API interface represents the service worker registration. You register a service worker to control one or more pages that share the same origin. + * Available only in secure contexts. + */ interface ServiceWorkerRegistration extends EventTarget { readonly active: ServiceWorker | null; readonly installing: ServiceWorker | null; @@ -2763,6 +2795,7 @@ declare var SharedWorkerGlobalScope: { new(): SharedWorkerGlobalScope; }; +/** Available only in secure contexts. */ interface StorageManager { estimate(): Promise; persisted(): Promise; @@ -2773,7 +2806,10 @@ declare var StorageManager: { new(): StorageManager; }; -/** This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). */ +/** + * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). + * Available only in secure contexts. + */ interface SubtleCrypto { decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; @@ -5050,6 +5086,7 @@ declare var WindowClient: { }; interface WindowOrWorkerGlobalScope { + /** Available only in secure contexts. */ readonly caches: CacheStorage; readonly crossOriginIsolated: boolean; readonly crypto: Crypto; @@ -5372,7 +5409,8 @@ declare namespace WebAssembly { var CompileError: { prototype: CompileError; - new(): CompileError; + new(message?: string): CompileError; + (message?: string): CompileError; }; interface Global { @@ -5399,7 +5437,8 @@ declare namespace WebAssembly { var LinkError: { prototype: LinkError; - new(): LinkError; + new(message?: string): LinkError; + (message?: string): LinkError; }; interface Memory { @@ -5428,7 +5467,8 @@ declare namespace WebAssembly { var RuntimeError: { prototype: RuntimeError; - new(): RuntimeError; + new(message?: string): RuntimeError; + (message?: string): RuntimeError; }; interface Table { @@ -5505,7 +5545,7 @@ interface PerformanceObserverCallback { } interface QueuingStrategySize { - (chunk?: T): number; + (chunk: T): number; } interface TransformerFlushCallback { @@ -5580,6 +5620,7 @@ declare function importScripts(...urls: (string | URL)[]): void; /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ declare function dispatchEvent(event: Event): boolean; declare var fonts: FontFaceSet; +/** Available only in secure contexts. */ declare var caches: CacheStorage; declare var crossOriginIsolated: boolean; declare var crypto: Crypto; @@ -5668,7 +5709,7 @@ type MediaDecodingType = "file" | "media-source" | "webrtc"; type MediaEncodingType = "record" | "webrtc"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; -type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock"; +type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking"; type PermissionState = "denied" | "granted" | "prompt"; type PredefinedColorSpace = "display-p3" | "srgb"; type PremultiplyAlpha = "default" | "none" | "premultiply"; diff --git a/lib/lib.webworker.iterable.d.ts b/lib/lib.webworker.iterable.d.ts index 756d5e72060a0..3d67660b716be 100644 --- a/lib/lib.webworker.iterable.d.ts +++ b/lib/lib.webworker.iterable.d.ts @@ -76,13 +76,6 @@ interface MessageEvent { initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable): void; } -interface ReadableStream { - [Symbol.iterator](): IterableIterator; - entries(): IterableIterator<[number, any]>; - keys(): IterableIterator; - values(): IterableIterator; -} - interface SubtleCrypto { deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: Iterable): Promise; generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise; diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 812b96a042a4e..af7d5e1eb0697 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "Etykieta nie jest dozwolona w tym miejscu.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Element krotki z etykietą jest deklarowany jako opcjonalny za pomocą znaku zapytania po nazwie i przed dwukropkiem, a nie po typie.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Oznaczony etykietą element krotki jest deklarowany jako reszta z \"...\" przed nazwą, a nie przed typem.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Zmapowany typ nie może deklarować właściwości ani metod.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicjator składowej w deklaracji wyliczenia nie może przywoływać składowych zadeklarowanych po nim, w tym składowych zdefiniowanych w innych wyliczeniach.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Klasa mixin musi mieć konstruktor z pojedynczym parametrem rest o typie „any[]”.", "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Klasa domieszki, która rozciąga się od zmiennej typu zawierającej sygnaturę konstrukcji abstrakcyjnej, musi być również zadeklarowana jako „abstract”.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Nie można odnaleźć nazwy „{0}”. Czy chcesz zainstalować definicje typów dla środowiska Node? Spróbuj użyć polecenia „npm i --save-dev @types/node”.", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Nie można odnaleźć nazwy \"{0}\". Czy chcesz zainstalować definicje typów dla węzła? Spróbuj użyć polecenia \"npm i --save-dev @types/node\", a następnie dodaj element \"node\" do pola types w pliku tsconfig.", "Cannot_find_namespace_0_2503": "Nie można odnaleźć przestrzeni nazw „{0}”.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Nie można odnaleźć przestrzeni nazw „{0}”. Czy chodziło Ci o „{1}”?", "Cannot_find_parameter_0_1225": "Nie można odnaleźć parametru „{0}”.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Nie można odnaleźć wspólnej ścieżki podkatalogu dla plików wejściowych.", "Cannot_find_type_definition_file_for_0_2688": "Nie można znaleźć pliku definicji typu dla elementu „{0}”.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Konwertuj listę przeciążeń na pojedynczą sygnaturę", "Convert_parameters_to_destructured_object_95075": "Konwertuj parametry na obiekt destrukturyzowany", "Convert_require_to_import_95047": "Konwertuj wywołanie „require” na wywołanie „import”", - "Convert_to_ES6_module_95017": "Konwertuj na moduł ES6", + "Convert_to_ES_module_95017": "Konwertuj na moduł ES", "Convert_to_a_bigint_numeric_literal_95091": "Konwertuj na literał liczbowy typu bigint", "Convert_to_anonymous_function_95123": "Konwertuj na funkcję anonimową", "Convert_to_arrow_function_95125": "Konwertuj na funkcję strzałki", @@ -561,7 +563,7 @@ "Duplicate_property_0_2718": "Zduplikowana właściwość „{0}”.", "Dynamic_import_cannot_have_type_arguments_1326": "Dynamiczny import nie może mieć argumentów typu.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Specyfikator dynamicznego importowania musi być typu „string”, ale określono typ „{0}”.", - "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323": "Dynamiczne importy są obsługiwane tylko wtedy, gdy flaga „--module” jest ustawiona na wartość „es2020”, „esnext”, „commonjs”, „amd”, „system”, „umd”, „node12” lub „nodenext”.", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Dynamiczne importy są obsługiwane tylko wtedy, gdy flaga „--module” jest ustawiona na „es2020”, „es2022”, „esnext”, „commonjs”, „amd”, „system”, „umd”, „node12” lub „nodenext”.", "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450": "Importy dynamiczne akceptują jako argumenty tylko specyfikator modułu i asercję opcjonalną", "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324": "Importy dynamiczne obsługują drugi argument tylko w przypadku, gdy opcja „--module” ma wartość „esnext”.", "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Każdy element członkowski typu unii „{0}” ma sygnatury konstrukcji, ale żadne z tych sygnatur nie są ze sobą zgodne.", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Nie można odnaleźć pliku '{0}'.", "File_Management_6245": "Zarządzanie plikami", "File_change_detected_Starting_incremental_compilation_6032": "Wykryto zmianę pliku. Trwa rozpoczynanie kompilacji przyrostowej...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Plik jest modułem CommonJS. Może zostać przekonwertowany na moduł ES6.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Plik jest modułem CommonJS; może zostać przekonwertowany na moduł ES.", "File_is_default_library_for_target_specified_here_1426": "Plik to domyślna biblioteka dla elementu docelowego określonego w tym miejscu.", "File_is_entry_point_of_type_library_specified_here_1419": "Plik to punkt wejścia biblioteki typów określonej w tym miejscu.", "File_is_included_via_import_here_1399": "Plik jest dołączony w tym miejscu za pomocą importu.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "Tag „@typedef” JSDoc powinien mieć adnotację typu lub powinien po nim następować tag „@property” lub „@member”.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Typy JSDoc mogą być używane wyłącznie w komentarzach dokumentacji.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Typy JSDoc mogą być przenoszone do typów TypeScript.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "Importy JSON są eksperymentalne w importach w trybie modułu ES.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Atrybuty JSX muszą mieć przypisane wyrażenie, które nie jest puste.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "Element JSX „{0}” nie ma odpowiedniego tagu zamykającego.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Klasa elementów JSX nie obsługuje atrybutów, ponieważ nie ma właściwości „{0}”.", @@ -1360,7 +1363,7 @@ "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Dla typu globalnego „JSX.{0}” nie można określić więcej niż jednej właściwości.", "The_implementation_signature_is_declared_here_2750": "Sygnatura implementacji jest zadeklarowana tutaj.", "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "Metawłaściwość „import.meta” jest niedozwolona w plikach, które będą kompilowane w danych wyjściowych CommonJS.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_system_node12__1343": "Metawłaściwość „import.meta” jest dozwolona tylko wtedy, gdy opcja „--module” ma wartość „es2020”, „esnext”, „system”, „node12” lub „nodenext”.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "Meta-właściwość „import.meta” jest dozwolona tylko wtedy, gdy opcja „--module” ma wartość „es2020”, „es2022”, „esnext”, „system”, „node12” lub „nodenext”.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Wywnioskowany typ „{0}” nie może być nazwany bez odwołania do elementu „{1}”. Prawdopodobnie nie jest to przenośne. Konieczna jest adnotacja typu.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Wywnioskowany typ elementu „{0}” odwołuje się do typu ze strukturą cykliczną, którego nie można serializować w prosty sposób. Wymagana jest adnotacja typu.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Wnioskowany typ „{0}” przywołuje niedostępny typ „{1}”. Adnotacja typu jest konieczna.", @@ -1459,9 +1462,9 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Ta składnia wymaga zaimportowanego pomocnika, ale nie można znaleźć modułu „{0}”.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Ta składnia wymaga zaimportowanego pomocnika o nazwie „{1}”, który nie istnieje w elemencie „{0}”. Rozważ uaktualnienie wersji „{0}”.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Ta składnia wymaga zaimportowanego pomocnika o nazwie „{1}” z parametrami {2}, który nie jest zgodny z tym w elemencie „{0}”. Rozważ uaktualnienie wersji elementu „{0}”.", - "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_noden_1378": "Pętle najwyższego poziomu „await” są dozwolone tylko wtedy, gdy opcja „module” jest ustawiona na wartość „esnext”, „system” lub „nodenext”, a opcja „target” jest ustawiona na wartość „es2017” lub wyższą.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378": "Wyrażenia „await” najwyższego poziomu są dozwolone tylko wtedy, gdy opcja „module” jest ustawiona na wartość „es2022”, „esnext”, „system” lub „nodenext”, a opcja „target” jest ustawiona na wartość „es2017” lub wyższą.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Deklaracje najwyższego poziomu w plikach .d.ts muszą rozpoczynać się od modyfikatora „declare” lub „export”.", - "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_nodenex_1432": "Pętle najwyższego poziomu „for await” są dozwolone tylko wtedy, gdy opcja „module” jest ustawiona na wartość „esnext”, „system” lub „nodenext”, a opcja „target” jest ustawiona na wartość „es2017” lub wyższą.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432": "Pętle najwyższego poziomu „for await” są dozwolone tylko wtedy, gdy opcja „module” jest ustawiona na wartość „es2022”, „esnext”, „system” lub „nodenext”, a opcja „target” jest ustawiona na wartość „es2017” lub wyższą.", "Trailing_comma_not_allowed_1009": "Końcowy przecinek jest niedozwolony.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpiluj każdy plik jako oddzielny moduł (podobne do „ts.transpileModule”).", "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Spróbuj użyć polecenia „npm i --save-dev @types/{1}”, jeśli istnieje, lub dodać nowy plik deklaracji (.d.ts) zawierający ciąg „declare module '{0}';”", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "Element „{0}” jest zdefiniowany jako metoda dostępu w klasie „{1}”, ale jest przesłaniany tutaj w elemencie „{2}” jako właściwość wystąpienia.", "_0_is_deprecated_6385": "Element „{0}” jest przestarzały.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "„{0}” nie jest prawidłową metawłaściwością słowa kluczowego „{1}”. Czy miał to być element „{2}”?", + "_0_is_not_allowed_as_a_parameter_name_1390": "„{0}” jest niedozwolone jako nazwa parametru.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "Element „{0}” nie jest dozwolony jako nazwa deklaracji zmiennej.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "Element „{0}” jest przywoływany bezpośrednio lub pośrednio w jego własnym wyrażeniu podstawowym.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "Element „{0}” jest przywoływany bezpośrednio lub pośrednio w jego własnej adnotacji typu.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 6c2b26dfab007..629804e85ae5b 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -2637,6 +2637,13 @@ declare namespace ts.server.protocol { * values, with insertion text to replace preceding `.` tokens with `?.`. */ readonly includeAutomaticOptionalChainCompletions?: boolean; + /** + * If enabled, completions for class members (e.g. methods and properties) will include + * a whole declaration for the member. + * E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of + * `class A { foo }`. + */ + readonly includeCompletionsWithClassMemberSnippets?: boolean; readonly allowIncompleteCompletions?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index a0da81495435f..1257f0cf2bed6 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "Um rótulo não é permitido aqui.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Um elemento de tupla rotulado é declarado como opcional com um ponto de interrogação depois do nome e antes de dois-pontos, em vez de depois do tipo.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Um elemento de tupla rotulado foi declarado como Rest com um '...' antes do nome, em vez de antes do tipo.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Um tipo mapeado não pode declarar propriedades ou métodos.", "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_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Uma classe mixin que se estende de uma variável de tipo contendo uma assinatura de constructo abstrata também precisa ser declarada como 'abstract'.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Não é possível localizar o nome '{0}'. Você precisa instalar definições de tipo para o nó? Tente `npm i --save-dev @types/node`.", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Não é possível encontrar o nome '{0}'. Você precisa instalar as definições de tipo para o nó? Tente `npm i --save-dev @types/node` e, em seguida, adicione 'node' ao campo tipos em seu tsconfig.", "Cannot_find_namespace_0_2503": "Não é possível encontrar o namespace '{0}'.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Não é possível localizar o namespace '{0}'. Você quis dizer '{1}'?", "Cannot_find_parameter_0_1225": "Não é possível encontrar o parâmetro '{0}'.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Não é possível encontrar o caminho do subdiretório comum para os arquivos de entrada.", "Cannot_find_type_definition_file_for_0_2688": "Não é possível encontrar o arquivo de definição de tipo para '{0}'.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Converter a lista de sobrecarga em assinatura única", "Convert_parameters_to_destructured_object_95075": "Converter parâmetros para objeto não estruturado", "Convert_require_to_import_95047": "Converter 'require' em 'import'", - "Convert_to_ES6_module_95017": "Converter em módulo ES6", + "Convert_to_ES_module_95017": "Converter em módulo ES", "Convert_to_a_bigint_numeric_literal_95091": "Converter para um literal numérico bigint", "Convert_to_anonymous_function_95123": "Converter em uma função anônima", "Convert_to_arrow_function_95125": "Converter em uma função de seta", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Arquivo '{0}' não encontrado.", "File_Management_6245": "Gerenciamento de Arquivos", "File_change_detected_Starting_incremental_compilation_6032": "Alteração do arquivo detectada. Iniciando compilação incremental...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "O arquivo é um módulo CommonJS; ele pode ser convertido em um módulo ES6.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "O arquivo é um módulo CommonJS; ele pode ser convertido em um módulo ES.", "File_is_default_library_for_target_specified_here_1426": "O arquivo é a biblioteca padrão para o destino especificado aqui.", "File_is_entry_point_of_type_library_specified_here_1419": "O arquivo é o ponto de entrada da biblioteca de tipos especificada aqui.", "File_is_included_via_import_here_1399": "O arquivo é incluído via importação aqui.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "A marca JSDoc \"@typedef\" deve ter uma anotação de tipo ou ser seguida pelas marcas \"@property\" or \"@member\".", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Os tipos de JSDoc podem ser usados somente dentro dos comentários de documentação.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Tipos JSDoc podem ser movidos para tipos TypeScript.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "As importações JSON são experimentais em importações de modo de módulo ES.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Os atributos JSX só devem ser atribuídos a 'expressões' que não estejam vazias.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "O elemento JSX '{0}' não tem uma marcação de fechamento correspondente.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "A classe do elemento JSX não dá suporte a atributos porque não tem uma propriedade '{0}'.", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' está definido como um acessador na classe '{1}', mas é substituído aqui em '{2}' como uma propriedade de instância.", "_0_is_deprecated_6385": "'{0}' foi preterido.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' não é uma metapropriedade para a palavra-chave '{1}'. Você quis dizer '{2}'?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' não é permitido como um nome de parâmetro.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' não é permitido como um nome de declaração de variável.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' é referenciado direta ou indiretamente em sua própria expressão base.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' é referenciado direta ou indiretamente em sua própria anotação de tipo.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index 53ff9cb9625a7..7d2c2cd66fc1c 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "Метка здесь запрещена.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Элемент маркированного кортежа объявлен как необязательный с вопросительным знаком между именем и двоеточием, а не после типа.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Маркированный элемент кортежа объявлен как rest с многоточием перед именем, а не перед типом.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Сопоставленный тип не может объявлять свойства и методы.", "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": "Класс примеси должен иметь конструктор с одиночным параметром REST типа any[].", "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Класс примеси, который наследуется от переменной типа, содержащей сигнатуру абстрактной конструкции, должен быть также объявлен как \"abstract\".", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "Не удается найти имя \"{0}\". Вы хотите установить определения типов для узла? Попробуйте использовать команду \"npm i --save-dev @types/node\".", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "Не удается найти имя \"{0}\". Вы хотите установить определения типов для узла? Попробуйте использовать `npm i --save-dev @types/node`, а затем добавьте \"node\" в поле типов в файле tsconfig.", "Cannot_find_namespace_0_2503": "Не удается найти пространство имен \"{0}\".", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Невозможно найти пространство имен \"{0}\". Вы имели в виду \"{1}\"?", "Cannot_find_parameter_0_1225": "Не удается найти параметр \"{0}\".", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Не удается найти общий путь к подкаталогу для входных файлов.", "Cannot_find_type_definition_file_for_0_2688": "Не удается найти файл определения типа для \"{0}\".", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Преобразовать список перегрузок в одиночную сигнатуру", "Convert_parameters_to_destructured_object_95075": "Преобразовать параметры в деструктурированный объект", "Convert_require_to_import_95047": "Преобразовать \"require\" в \"import\"", - "Convert_to_ES6_module_95017": "Преобразовать в модуль ES6", + "Convert_to_ES_module_95017": "Преобразовать в модуль ES", "Convert_to_a_bigint_numeric_literal_95091": "Преобразовать в числовой литерал типа bigint", "Convert_to_anonymous_function_95123": "Преобразовать в анонимную функцию", "Convert_to_arrow_function_95125": "Преобразовать в стрелочную функцию", @@ -561,7 +563,7 @@ "Duplicate_property_0_2718": "Повторяющееся свойство \"{0}\".", "Dynamic_import_cannot_have_type_arguments_1326": "При динамическом импорте не могут использоваться аргументы типов.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Описатель динамического импорта должен иметь тип \"string\", но имеет тип \"{0}\".", - "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323": "Динамические импорты поддерживаются только в том случае, если флаг \"--module\" имеет значение \"es2020\", \"esnext\", \"commonjs\", \"amd\", \"system\", \"umd\", \"node12\" или \"nodenext\".", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Динамический импорт поддерживаются только в том случае, если флагу \"--module\" присвоено значение \"es2020\", \"es2022\", \"esnext\", \"commonjs\", \"amd\", \"system\", \"umd\", \"node12\" или \"nodenext\".", "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450": "Динамические импорты могут принять спецификатор модуля и необязательное утверждение в качестве аргументов", "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324": "Динамические импорты поддерживают второй аргумент, только если параметр \"--module\" имеет значение \"esnext\".", "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "Каждый член типа объединения \"{0}\" имеет сигнатуры конструкций, но ни одна из их не совместима с другими.", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "Файл \"{0}\" не найден.", "File_Management_6245": "Управление файлами", "File_change_detected_Starting_incremental_compilation_6032": "Обнаружено изменение в файле. Запускается инкрементная компиляция...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Файл является модулем CommonJS; его можно преобразовать в модуль ES6.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Файл является модулем CommonJS. Его можно преобразовать в модуль ES.", "File_is_default_library_for_target_specified_here_1426": "Файл является библиотекой по умолчанию для указанного здесь целевого объекта.", "File_is_entry_point_of_type_library_specified_here_1419": "Файл является точкой входа для указанной здесь библиотеки типов.", "File_is_included_via_import_here_1399": "Файл включается с помощью импорта.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "У тега \"@typedef\" JSDoc должна быть аннотация типа, или после него должны стоять теги \"@property\" или \"@member\".", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "Типы JSDoc можно использовать только в комментариях в документации.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "Типы JSDoc могут быть преобразованы в типы TypeScript.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "Импорт данных JSON — экспериментальная функция импорта в режиме модуля ES.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "Атрибутам JSX должно назначаться только непустое \"expression\".", "JSX_element_0_has_no_corresponding_closing_tag_17008": "Элемент JSX \"{0}\" не содержит соответствующий закрывающий тег.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "Класс элементов JSX не поддерживает атрибуты, так как не имеет свойства \"{0}\".", @@ -1360,7 +1363,7 @@ "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.", "The_implementation_signature_is_declared_here_2750": "Здесь объявлена сигнатура реализации.", "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "Метасвойство \"import.meta\" не разрешено в файлах, которые будут построены в выходных данных CommonJS.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_system_node12__1343": "Метасвойство \"import.meta\" разрешено, только когда параметр \"--module\" имеет значение \"es2020\", \"esnext\", \"system\", \"node12\" или \"nodenext\".", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "Метасвойство \"import.meta\" допускается, только если параметру \"--module\" присвоено значение \"es2020\", \"es2022\", \"esnext\", \"system\", \"node12\" или \"nodenext\".", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Выводимому типу \"{0}\" невозможно присвоить имя без ссылки на \"{1}\". Вероятно, оно не является переносимым. Требуется заметка с типом.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Выводимый тип \"{0}\" ссылается на тип с циклической структурой, которая не может быть элементарно сериализована. Требуется заметка с типом.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Выведенный тип \"{0}\" ссылается на недоступный тип \"{1}\". Требуется аннотация типа.", @@ -1459,9 +1462,9 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Для этого синтаксиса требуется импортированный вспомогательный объект, но найти модуль \"{0}\" не удается.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Для этого синтаксиса требуется импортированный вспомогательный объект с именем \"{1}\", который не существует в \"{0}\". Рекомендуется обновить версию \"{0}\".", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Для этого синтаксиса требуется импортированный вспомогательный объект с именем \"{1}\" и параметрами ({2}), который не совместим с объектом в \"{0}\". Попробуйте обновить версию \"{0}\".", - "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_noden_1378": "Выражения \"await\" верхнего уровня допускаются, только если для параметра \"module\" задано значение \"esnext\", \"system\" или \"nodenext\", а для параметра \"target\" задано значение \"es2017\" или выше.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378": "Выражения \"await\" верхнего уровня допускаются, только если параметру \"module\" присвоено значение \"es2022\", \"esnext\", \"system\" или \"nodenext\", а параметру \"target\" присвоено значение \"es2017\" или выше.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": "Объявления верхнего уровня в файлах .d.ts должны начинаться с модификатора \"declare\" или \"export\".", - "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_nodenex_1432": "Циклы \"for await\" верхнего уровня допускаются, только если для параметра \"module\" задано значение \"esnext\", \"system\" или \"nodenext\", а для параметра \"target\" задано значение \"es2017\" или выше.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432": "Циклы \"for await\" верхнего уровня допускаются, только если параметру \"module\" присвоено значение \"es2022\", \"esnext\", \"system\" или \"nodenext\", а параметру \"target\" присвоено значение \"es2017\" или выше.", "Trailing_comma_not_allowed_1009": "Завершающая запятая запрещена.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Транскомпиляция каждого файла как отдельного модуля (аналогично ts.transpileModule).", "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Попробуйте использовать команду \"npm i --save-dev @types/{1}\", если он существует, или добавьте новый файл объявления (.d.ts), содержащий \"declare module '{0}';\".", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "\"{0}\" определен как метод доступа в классе \"{1}\", но переопределяется здесь в \"{2}\" как свойство экземпляра.", "_0_is_deprecated_6385": "\"{0}\" устарело.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "\"{0}\" не является допустимым метасвойством для ключевого слова \"{1}\". Вы имели в виду \"{2}\"?", + "_0_is_not_allowed_as_a_parameter_name_1390": "\"{0}\" не является допустимым именем параметра.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "Использование \"{0}\" в качестве имени объявления переменной не допускается.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "На \"{0}\" есть прямые или непрямые ссылки в его собственном базовом выражении.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "На \"{0}\" есть прямые или непрямые ссылки в его собственной аннотации типа.", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 5d5c250aeef65..ba4055a3773a2 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "'Burada etikete izin verilmiyor.", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "Etiketli demet öğesi türden sonra değil, addan sonra ve iki nokta işaretinden önce bir soru işareti ile isteğe bağlı olarak bildirilir.", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "Etiketlenmiş bir demet öğesi, tür yerine addan önce '...' ile bekleyen olarak bildirilir.", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "Eşlenmiş bir tür özellik veya metot bildiremez.", "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_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "Soyut yapı imzası içeren bir tür değişkeninden genişleyen mixin sınıfı da 'soyut' olarak bildirilmelidir.", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "'{0}' adı bulunamıyor. Düğüm için tür tanımlarını yüklemeniz mi gerekiyor? Şunu deneyin: `npm i --save-dev @types/node`.", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "'{0}' adı bulunamıyor. Düğüm için tür tanımlarını yüklemeniz mi gerekiyor? Şunu deneyin: `npm i --save-dev @types/node`. Ardından tsconfig dosyanızdaki türler alanına 'node' ekleyin.", "Cannot_find_namespace_0_2503": "'{0}' ad alanı bulunamıyor.", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "Ad alanı '{0}' bulunamıyor. Bunu mu demek istediniz: '{1}'?", "Cannot_find_parameter_0_1225": "'{0}' parametresi bulunamıyor.", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "Giriş dosyalarına ait ortak alt dizin yolu bulunamıyor.", "Cannot_find_type_definition_file_for_0_2688": "'{0}' için tür tanımı dosyası bulunamıyor.", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "Aşırı yükleme listesini tek imzaya dönüştür", "Convert_parameters_to_destructured_object_95075": "Parametreleri, bozulan nesneye dönüştürün", "Convert_require_to_import_95047": "'require' öğesini 'import' olarak dönüştür", - "Convert_to_ES6_module_95017": "ES6 modülüne dönüştür", + "Convert_to_ES_module_95017": "ES modülüne dönüştür", "Convert_to_a_bigint_numeric_literal_95091": "Büyük tamsayı sayısal sabit değerine dönüştürün", "Convert_to_anonymous_function_95123": "Anonim işleve dönüştür", "Convert_to_arrow_function_95125": "Ok işlevine dönüştür", @@ -561,7 +563,7 @@ "Duplicate_property_0_2718": "'{0}' özelliğini yineleyin.", "Dynamic_import_cannot_have_type_arguments_1326": "Dinamik içeri aktarma, tür bağımsız değişkenleri içeremez.", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "Dinamik içeri aktarmanın tanımlayıcısı 'string' türünde olmalıdır, ancak buradaki tür: '{0}'.", - "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323": "Dinamik içeri aktarmalar yalnızca '--module' bayrağı 'es2020', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node12' veya 'nodenext' olarak ayarlandığında desteklenir.", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "Dinamik içeri aktarmalar yalnızca '--module' bayrağı 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node12' veya 'nodenext' olarak ayarlandığında desteklenir.", "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450": "Dinamik içeri aktarmalar, bağımsız değişken olarak yalnızca bir modül tanımlayıcısı ve isteğe bağlı bir onay kabul edebilir", "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324": "Dinamik içeri aktarmalar yalnızca '--module' seçeneği 'esnext' olarak ayarlandığında ikinci bir bağımsız değişkeni destekler.", "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "'{0}' birleşim türünün her bir üyesi yapı imzalarına sahip ancak bu imzaların hiçbiri birbiriyle uyumlu değil.", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "'{0}' dosyası bulunamadı.", "File_Management_6245": "Dosya Yönetimi", "File_change_detected_Starting_incremental_compilation_6032": "Dosya değişikliği algılandı. Artımlı derleme başlatılıyor...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "Bir CommonJS modülü olan dosya, ES6 modülüne dönüştürülebilir.", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "Bir CommonJS modülü olan dosya bir ES modülüne dönüştürülebilir.", "File_is_default_library_for_target_specified_here_1426": "Burada dosya, belirtilen hedef için varsayılan kitaplıktır.", "File_is_entry_point_of_type_library_specified_here_1419": "Burada dosya, belirtilen tür kitaplığının giriş noktasıdır.", "File_is_included_via_import_here_1399": "Burada dosya, içeri aktarma aracılığıyla eklenmiştir.", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' etiketi bir tür ek açıklamasına sahip olmalıdır veya sonrasında '@property' ya da '@member' etiketlerinden biri gelmelidir.", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc türleri yalnızca belge açıklamalarının içinde kullanılabilir.", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc türleri TypeScript türlerine taşınabilir.", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "JSON içeri aktarmaları, ES modül modu içeri aktarmaları için deneyseldir.", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "JSX özniteliklerine yalnızca boş olmayan 'expression' ifadesi atanabilir.", "JSX_element_0_has_no_corresponding_closing_tag_17008": "'{0}' adlı JSX öğesine karşılık gelen bir kapatma etiketi yok.", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX öğe sınıfı, '{0}' özelliğine sahip olmadığı için öznitelikleri desteklemiyor.", @@ -1360,7 +1363,7 @@ "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "'JSX.{0}' genel türü birden fazla özelliğe sahip olamaz.", "The_implementation_signature_is_declared_here_2750": "Uygulama imzası burada bildirilir.", "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "CommonJS çıkışında oluşturulacak dosyalarda 'import.meta' meta özelliğine izin verilmiyor.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_system_node12__1343": "'import.meta' meta özelliğine yalnızca '--module' seçeneği 'es2020', 'esnext', 'system', 'node12' veya 'nodenext' olduğunda izin verilir.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "'import.meta' meta özelliğine yalnızca '--module' seçeneği 'es2020', 'es2022', 'esnext', 'system', 'node12' veya 'nodenext' olduğunda izin verilir.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}' öğesinin çıkarsanan türü, '{1}' başvurusu olmadan adlandırılamaz. Bu büyük olasılıkla taşınabilir değildir. Tür ek açıklaması gereklidir.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Çıkarsanan '{0}' türü, önemsiz olarak seri hale getirilemeyen döngüsel yapıya sahip bir türe başvurur. Tür ek açıklaması gerekir.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Çıkarsanan '{0}' türü, erişilemeyen bir '{1}' türüne başvuruyor. Tür ek açıklaması gereklidir.", @@ -1459,9 +1462,9 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Bu söz dizimi, içeri aktarılan bir yardımcı gerektiriyor ancak '{0}' modülü bulunamıyor.", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "Bu söz dizimi, '{0}' içinde bulunmayan '{1}' adlı içeri aktarılmış bir yardımcı gerektirir. '{0}' sürümünüzü yükseltmeyi deneyin.", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "Bu söz dizimi, '{0}' içindeki yardımcı ile uyumlu olmayan, {2} parametreye sahip '{1}' adlı içeri aktarılan yardımcıyı gerektiriyor. '{0}' sürümünüzü yükseltmeyi düşünün.", - "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_noden_1378": "Üst düzey 'for await' ifadelerine yalnızca 'module' seçeneği 'esnext', 'system' veya 'nodenext' olarak ayarlandığında ve 'target' seçeneği 'es2017' veya üzeri olarak ayarlandığında izin verilir.", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378": "Üst düzey 'await' ifadelerine yalnızca 'module' seçeneği 'es2022', 'esnext', 'system' veya 'nodenext' olarak ayarlandığında ve 'target' seçeneği 'es2017' veya üzeri olarak ayarlandığında izin verilir.", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts dosyalarındaki üst düzey bildirimler bir 'declare' veya 'export' değiştiricisi ile başlamalıdır.", - "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_nodenex_1432": "Üst düzey 'for await' döngülerine yalnızca 'module' seçeneği 'esnext', 'system' veya 'nodenext' olarak ayarlandığında ve 'target' seçeneği 'es2017' veya üzeri olarak ayarlandığında izin verilir.", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432": "Üst düzey 'for await' döngülerine yalnızca 'module' seçeneği 'es2022', 'esnext', 'system' veya 'nodenext' olarak ayarlandığında ve 'target' seçeneği 'es2017' veya üzeri olarak ayarlandığında izin verilir.", "Trailing_comma_not_allowed_1009": "Sona eklenen virgüle izin verilmez.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Her dosyayı ayrı bir modül olarak derleyin ('ts.transpileModule' gibi).", "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "Varsa `npm i --save-dev @types/{1}` deneyin veya `declare module '{0}';` deyimini içeren yeni bir bildirim (.d.ts) dosyası ekleyin", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}', '{1}' sınıfında bir erişimci olarak tanımlandı ancak burada, '{2}' içinde örnek özelliği olarak geçersiz kılındı.", "_0_is_deprecated_6385": "'{0}' kullanım dışı bırakıldı.", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}', '{1}' anahtar sözcüğü için geçerli bir meta özellik değil. Bunu mu demek istediniz: '{2}'?", + "_0_is_not_allowed_as_a_parameter_name_1390": "'{0}' öğesine parametre adı olarak izin verilmiyor.", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' öğesinin değişken bildirim adı olarak kullanılmasına izin verilmiyor.", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' öğesine kendi temel ifadesinde doğrudan veya dolaylı olarak başvuruluyor.", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' öğesine kendi tür ek açıklamasında doğrudan veya dolaylı olarak başvuruluyor.", diff --git a/lib/tsc.js b/lib/tsc.js index d37257087d429..e8b733568bb60 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -22,7 +22,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -69,7 +69,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) { var ts; (function (ts) { ts.versionMajorMinor = "4.5"; - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.5.2"; var NativeCollections; (function (NativeCollections) { function tryGetNativeMap() { @@ -80,19 +80,19 @@ var ts; return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; - })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { + })(NativeCollections || (NativeCollections = {})); + ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); + ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); function getCollectionImplementation(name, nativeFactory, shimFactory) { var _a; - var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator); + var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); if (constructor) return constructor; throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation."); } - ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); - ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); +})(ts || (ts = {})); +var ts; +(function (ts) { function getIterator(iterable) { if (iterable) { if (isArray(iterable)) @@ -2129,6 +2129,10 @@ var ts; return formatEnum(kind, ts.SyntaxKind, false); } Debug.formatSyntaxKind = formatSyntaxKind; + function formatSnippetKind(kind) { + return formatEnum(kind, ts.SnippetKind, false); + } + Debug.formatSnippetKind = formatSnippetKind; function formatNodeFlags(flags) { return formatEnum(flags, ts.NodeFlags, true); } @@ -4972,7 +4976,7 @@ var ts; } } function readDirectory(path, extensions, excludes, includes, depth) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { var originalStackTraceLimit = Error.stackTraceLimit; @@ -5052,6 +5056,10 @@ var ts; } return sys; })(); + function setSys(s) { + ts.sys = s; + } + ts.setSys = setSys; if (ts.sys && ts.sys.getEnvironmentVariable) { setCustomPollingValues(ts.sys); ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) @@ -5359,6 +5367,7 @@ var ts; Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."), Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), + _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -5900,6 +5909,9 @@ var ts; Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), 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}'."), @@ -6006,6 +6018,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), 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}'."), @@ -6558,6 +6571,8 @@ var ts; If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."), + A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."), + JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."), 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_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."), @@ -6613,7 +6628,7 @@ var ts; Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."), This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), @@ -6661,6 +6676,7 @@ var ts; Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"), Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), + Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), 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_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -6675,7 +6691,7 @@ var ts; 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"), + Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"), Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), @@ -15525,6 +15541,8 @@ var ts; case ts.ModuleKind.ES2020: case ts.ModuleKind.ES2022: case ts.ModuleKind.ESNext: + case ts.ModuleKind.Node12: + case ts.ModuleKind.NodeNext: return true; default: return false; @@ -15848,7 +15866,7 @@ var ts; return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); } ts.getRegexFromPattern = getRegexFromPattern; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -15860,9 +15878,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - if (directoryExists(basePath)) { - visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); - } + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -15949,10 +15965,14 @@ var ts; var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { case ".js": + case ".cjs": + case ".mjs": return 1; case ".jsx": return 2; case ".ts": + case ".cts": + case ".mts": return 3; case ".tsx": return 4; @@ -16498,6 +16518,10 @@ var ts; return node.kind === 212 || node.kind === 213; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; + function escapeSnippetText(text) { + return text.replace(/\$/gm, "\\$"); + } + ts.escapeSnippetText = escapeSnippetText; })(ts || (ts = {})); var ts; (function (ts) { @@ -18324,23 +18348,25 @@ var ts; ? update(createIndexedAccessTypeNode(objectType, indexType), node) : node; } - function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { + function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { var node = createBaseNode(194); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; node.questionToken = questionToken; node.type = type; + node.members = members && createNodeArray(members); node.transformFlags = 1; return node; } - function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) { + function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) { return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type - ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node) + || node.members !== members + ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } function createLiteralTypeNode(literal) { @@ -21687,6 +21713,17 @@ var ts; } } ts.moveEmitHelpers = moveEmitHelpers; + function getSnippetElement(node) { + var _a; + return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement; + } + ts.getSnippetElement = getSnippetElement; + function setSnippetElement(node, snippet) { + var emitNode = getOrCreateEmitNode(node); + emitNode.snippetElement = snippet; + return node; + } + ts.setSnippetElement = setSnippetElement; function ignoreSourceNewlines(node) { getOrCreateEmitNode(node).flags |= 134217728; return node; @@ -23974,7 +24011,8 @@ var ts; visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) || + visitNodes(cbNode, cbNodes, node.members); case 195: return visitNode(cbNode, node.literal); case 196: @@ -25725,7 +25763,10 @@ var ts; case 12: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected); case 15: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected); case 17: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); - case 16: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); + case 16: + return ts.isKeyword(token()) + ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_parameter_name, ts.tokenToString(token())) + : parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); case 19: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected); case 20: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected); case 21: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected); @@ -26319,8 +26360,9 @@ var ts; } var type = parseTypeAnnotation(); parseSemicolon(); + var members = parseList(4, parseTypeMember); parseExpected(19); - return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos); + return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } function parseTupleElementType() { var pos = getNodePos(); @@ -29011,16 +29053,21 @@ var ts; var pos = getNodePos(); parseExpected(129); var openBracePosition = scanner.getTokenPos(); - parseExpected(18); - var multiLine = scanner.hasPrecedingLineBreak(); - var elements = parseDelimitedList(24, parseAssertEntry, true); - if (!parseExpected(19)) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { - ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + if (parseExpected(18)) { + var multiLine = scanner.hasPrecedingLineBreak(); + var elements = parseDelimitedList(24, parseAssertEntry, true); + if (!parseExpected(19)) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { + ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + } } + return finishNode(factory.createAssertClause(elements, multiLine), pos); + } + else { + var elements = createNodeArray([], getNodePos(), undefined, false); + return finishNode(factory.createAssertClause(elements, false), pos); } - return finishNode(factory.createAssertClause(elements, multiLine), pos); } function tokenAfterImportDefinitelyProducesImportDeclaration() { return token() === 41 || token() === 18; @@ -29787,8 +29834,9 @@ var ts; return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); - var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var isMarkdownOrJSDocLink = token() === 22 + || lookAhead(function () { return nextTokenJSDoc() === 59 && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference(); var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } @@ -30654,7 +30702,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1, "react-native": 3, @@ -30770,6 +30818,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: "false", }, { name: "excludeDirectories", @@ -30804,11 +30853,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, + defaultValueDescription: "false", }, { name: "help", shortName: "?", - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "watch", @@ -30818,6 +30869,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, + defaultValueDescription: "false", }, { name: "preserveWatchOutput", @@ -30825,7 +30877,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "listFiles", @@ -30838,7 +30890,8 @@ var ts; name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, - description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included + description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: "false", }, { name: "listEmittedFiles", @@ -30909,7 +30962,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, - description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it + description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: "false", }, { name: "locale", @@ -30952,6 +31006,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, + defaultValueDescription: "false", }, { name: "version", @@ -30960,6 +31015,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: "false", }, { name: "init", @@ -30967,6 +31023,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: "false", }, { name: "project", @@ -30984,7 +31041,8 @@ var ts; shortName: "b", showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: "false", }, { name: "showConfig", @@ -30992,7 +31050,8 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, - description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: "false", }, { name: "listFilesOnly", @@ -31001,7 +31060,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, isCommandLineOnly: true, - description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: "false", }, ts.targetOptionDeclaration, { @@ -31120,7 +31180,6 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, transpileOptionValue: undefined, - defaultValueDescription: "n/a" }, { name: "outDir", @@ -31131,7 +31190,6 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files, - defaultValueDescription: "n/a" }, { name: "rootDir", @@ -31285,6 +31343,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: "false", }, { name: "alwaysStrict", @@ -31316,7 +31375,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined + description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: "false", }, { name: "noImplicitReturns", @@ -31332,21 +31392,24 @@ var ts; affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements + description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: "false", }, { name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Include_undefined_in_index_signature_results + description: ts.Diagnostics.Include_undefined_in_index_signature_results, + defaultValueDescription: "false", }, { name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: "false", }, { name: "noPropertyAccessFromIndexSignature", @@ -31361,6 +31424,8 @@ var ts; type: new ts.Map(ts.getEntries({ node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, + node12: ts.ModuleResolutionKind.Node12, + nodenext: ts.ModuleResolutionKind.NodeNext, })), affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, @@ -31448,7 +31513,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "allowUmdGlobalAccess", @@ -31495,7 +31560,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators + description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, + defaultValueDescription: "false", }, { name: "emitDecoratorMetadata", @@ -31503,7 +31569,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files + description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: "false", }, { name: "jsxFactory", @@ -31544,7 +31611,6 @@ var ts; category: ts.Diagnostics.Backwards_Compatibility, paramType: ts.Diagnostics.FILE, transpileOptionValue: undefined, - defaultValueDescription: "n/a", description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead, }, { @@ -31621,6 +31687,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: "false", }, { name: "disableSizeLimit", @@ -31635,21 +31702,24 @@ var ts; type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects + description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: "false", }, { name: "disableSolutionSearching", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing + description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: "false", }, { name: "disableReferencedProjectLoad", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript + description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: "false", }, { name: "noImplicitUseStrict", @@ -31682,7 +31752,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "declarationDir", @@ -31693,7 +31763,6 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files, - defaultValueDescription: "n/a" }, { name: "skipLibCheck", @@ -31775,6 +31844,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: "false", }, { name: "keyofStringsOnly", @@ -31812,27 +31882,31 @@ var ts; shortName: "v", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "dry", shortName: "d", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "force", shortName: "f", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", } ]; ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild, true), ts.optionsForBuild, true); @@ -31840,10 +31914,12 @@ var ts; { name: "enableAutoDiscovery", type: "boolean", + defaultValueDescription: "false", }, { name: "enable", type: "boolean", + defaultValueDescription: "false", }, { name: "include", @@ -31864,6 +31940,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", + defaultValueDescription: "false", }, ]; function createOptionNameMap(optionDeclarations) { @@ -34699,11 +34776,15 @@ var ts; if (!scope || !scope.packageJsonContent.exports) { return undefined; } + if (typeof scope.packageJsonContent.name !== "string") { + return undefined; + } var parts = ts.getPathComponents(moduleName); - if (scope.packageJsonContent.name !== parts[1]) { + var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } - var trailingParts = parts.slice(2); + var trailingParts = parts.slice(nameParts.length); return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : "." + ts.directorySeparator + trailingParts.join(ts.directorySeparator), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { @@ -37422,6 +37503,7 @@ var ts; case 168: case 171: case 172: + case 169: var containingClass = thisContainer.parent; var symbolTable = ts.isStatic(thisContainer) ? containingClass.symbol.exports : containingClass.symbol.members; if (ts.hasDynamicName(node)) { @@ -38480,6 +38562,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isPropertyAccessible: isPropertyAccessible, getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration, + getMemberOverrideModifierStatus: getMemberOverrideModifierStatus, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -38712,6 +38795,17 @@ var ts; var enumRelation = new ts.Map(); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var suggestedExtensions = [ + [".mts", ".mjs"], + [".ts", ".js"], + [".cts", ".cjs"], + [".mjs", ".mjs"], + [".js", ".js"], + [".cjs", ".cjs"], + [".tsx", compilerOptions.jsx === 1 ? ".jsx" : ".js"], + [".jsx", ".jsx"], + [".json", ".json"], + ]; initializeTypeChecker(); return checker; function getJsxNamespace(location) { @@ -39343,11 +39437,11 @@ var ts; } } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, issueSuggestions) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, issueSuggestions); + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, issueSuggestions) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { var _a, _b, _c; var originalLocation = location; var result; @@ -39592,7 +39686,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (issueSuggestions && suggestionCount < maximumSuggestionCount) { + if (suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -39601,7 +39695,9 @@ var ts; if (suggestion) { var suggestionName = symbolToString(suggestion); var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, false); - var message = isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; + var message = meaning === 1920 || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 + : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 + : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { @@ -39996,6 +40092,10 @@ var ts; function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === ts.ModuleKind.ESNext && targetMode === ts.ModuleKind.CommonJS; } + function isOnlyImportedAsDefault(usage) { + var usageMode = getUsageModeForExpression(usage); + return usageMode === ts.ModuleKind.ESNext && ts.endsWith(usage.text, ".json"); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { var usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== undefined) { @@ -40034,8 +40134,9 @@ var ts; exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", node, dontResolveAlias); } var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); + var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier); - if (!exportDefaultSymbol && !hasSyntheticDefault) { + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; var exportEqualsSymbol = moduleSymbol.exports.get("export="); @@ -40049,7 +40150,7 @@ var ts; reportNonDefaultExport(moduleSymbol, node); } } - else if (hasSyntheticDefault) { + else if (hasSyntheticDefault || hasDefaultOnly) { var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, false); return resolved; @@ -40153,7 +40254,7 @@ var ts; var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default") { var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); - if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } @@ -40463,7 +40564,7 @@ var ts; if (name.kind === 79) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true)); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true, false)); if (!symbol) { return getMergedSymbol(symbolFromJSPrototype); } @@ -40498,21 +40599,28 @@ var ts; var namespaceName = getFullyQualifiedName(namespace); var declarationName = ts.declarationNameToString(right); var suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); - var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968)); - var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); - var canSuggestTypeof = containingQualifiedName && !ts.isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (suggestionForNonexistentModule) { error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + return undefined; } - else if (canSuggestTypeof) { + var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); + var canSuggestTypeof = globalObjectType + && (meaning & 788968) + && containingQualifiedName + && !ts.isTypeOfExpression(containingQualifiedName.parent) + && tryGetQualifiedNameAsValue(containingQualifiedName); + if (canSuggestTypeof) { error(containingQualifiedName, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.entityNameToString(containingQualifiedName)); + return undefined; } - else if (meaning & 1920 && exportedTypeSymbol && ts.isQualifiedName(name.parent)) { - error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); - } - else { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + if (meaning & 1920 && ts.isQualifiedName(name.parent)) { + var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968)); + if (exportedTypeSymbol) { + error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); + return undefined; + } } + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); } return undefined; } @@ -40600,7 +40708,7 @@ var ts; : undefined; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - var _a, _b, _c, _d, _e, _f; + var _a, _b, _c, _d, _e, _f, _g; if (isForAugmentation === void 0) { isForAugmentation = false; } if (ts.startsWith(moduleReference, "@types/")) { var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -40620,7 +40728,8 @@ var ts; ((_d = ts.findAncestor(location, ts.isExportDeclaration)) === null || _d === void 0 ? void 0 : _d.moduleSpecifier) || ((_e = (ts.isModuleDeclaration(location) ? location : location.parent && ts.isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)) === null || _e === void 0 ? void 0 : _e.name) || ((_f = (ts.isLiteralImportTypeNode(location) ? location : undefined)) === null || _f === void 0 ? void 0 : _f.argument.literal); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : undefined); + var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -40633,6 +40742,9 @@ var ts; if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) { error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); } + if (mode === ts.ModuleKind.ESNext && compilerOptions.resolveJsonModule && resolvedModule.extension === ".json") { + error(errorNode, ts.Diagnostics.JSON_imports_are_experimental_in_ES_module_mode_imports); + } } return getMergedSymbol(sourceFile.symbol); } @@ -40674,6 +40786,10 @@ var ts; } else { var tsExtension = ts.tryExtractTSExtension(moduleReference); + var isExtensionlessRelativePathImport = ts.pathIsRelative(moduleReference) && !ts.hasExtension(moduleReference); + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var resolutionIsNode12OrNext = moduleResolutionKind === ts.ModuleResolutionKind.Node12 || + moduleResolutionKind === ts.ModuleResolutionKind.NodeNext; if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension); @@ -40689,6 +40805,19 @@ var ts; ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } + else if (mode === ts.ModuleKind.ESNext && resolutionIsNode12OrNext && isExtensionlessRelativePathImport) { + var absoluteRef_1 = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(currentSourceFile.path)); + var suggestedExt = (_g = suggestedExtensions.find(function (_a) { + var actualExt = _a[0], _importExt = _a[1]; + return host.fileExists(absoluteRef_1 + actualExt); + })) === null || _g === void 0 ? void 0 : _g[1]; + if (suggestedExt) { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + } + else { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -40752,39 +40881,47 @@ var ts; error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } - if (ts.getESModuleInterop(compilerOptions)) { - var referenceParent = referencingLocation.parent; - if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || - ts.isImportCall(referenceParent)) { - var type = getTypeOfSymbol(symbol); + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var reference = ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier; + var type = getTypeOfSymbol(symbol); + var defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); + if (defaultOnlyType) { + return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); + } + if (ts.getESModuleInterop(compilerOptions)) { var sigs = getSignaturesOfStructuredType(type, 0); if (!sigs || !sigs.length) { sigs = getSignaturesOfStructuredType(type, 1); } - if (sigs && sigs.length) { - var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier); - 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 = new ts.Map(symbol.members); - if (symbol.exports) - result.exports = new ts.Map(symbol.exports); - var resolvedModuleType = resolveStructuredTypeMembers(moduleType); - result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.indexInfos); - return result; + if ((sigs && sigs.length) || getPropertyOfType(type, "default")) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); + return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } } } } return symbol; } + function cloneTypeAsModuleType(symbol, moduleType, referenceParent) { + 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 = new ts.Map(symbol.members); + if (symbol.exports) + result.exports = new ts.Map(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.indexInfos); + return result; + } function hasExportAssignmentSymbol(moduleSymbol) { return moduleSymbol.exports.get("export=") !== undefined; } @@ -40813,8 +40950,8 @@ var ts; if (exportEquals !== moduleSymbol) { var type = getTypeOfSymbol(exportEquals); if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { - getPropertiesOfType(type).forEach(function (symbol) { - cb(symbol, symbol.escapedName); + forEachPropertyOfType(type, function (symbol, escapedName) { + cb(symbol, escapedName); }); } } @@ -41114,12 +41251,15 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + if (isNamedMember(symbol, id)) { (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } + function isNamedMember(member, escapedName) { + return !isReservedMemberName(escapedName) && symbolIsValue(member); + } function getNamedOrIndexSignatureMembers(members) { var result = getNamedMembers(members); var index = getIndexSymbolFromSymbolTable(members); @@ -41905,7 +42045,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined; var templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & 4)), context); - var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode); + var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, undefined); context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1); } @@ -47035,6 +47175,16 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function forEachPropertyOfType(type, action) { + type = getReducedApparentType(type); + if (type.flags & 3670016) { + resolveStructuredTypeMembers(type).members.forEach(function (symbol, escapedName) { + if (isNamedMember(symbol, escapedName)) { + action(symbol, escapedName); + } + }); + } + } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { var list = obj.properties; return list.some(function (property) { @@ -47833,7 +47983,7 @@ var ts; return false; switch (node.kind) { case 79: - return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; case 166: case 168: case 171: @@ -49057,6 +49207,8 @@ var ts; } if (!(flags & 131072)) { includes |= flags & 205258751; + if (flags & 465829888) + includes |= 33554432; if (type === wildcardType) includes |= 8388608; if (!strictNullChecks && flags & 98304) { @@ -49153,7 +49305,7 @@ var ts; var _loop_16 = function () { i--; var t = types[i]; - if (t.flags & 128 && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) { + if (t.flags & 128 && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { ts.orderedRemoveItemAt(types, i); } }; @@ -49249,7 +49401,7 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576, reducedTypes); } } - var objectFlags = (includes & 468598819 ? 0 : 65536) | + var objectFlags = (includes & 36323363 ? 0 : 65536) | (includes & 2097152 ? 33554432 : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } @@ -50115,12 +50267,6 @@ var ts; } return type[cache] = type; } - function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { - var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); - var checkType = type.checkType; - var extendsType = type.extendsType; - return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); - } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -50372,6 +50518,10 @@ var ts; } return result; } + function isDistributionDependent(root) { + return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || + isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType)); + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -51107,7 +51257,9 @@ var ts; return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 | 58982400 | 524288 | 2097152) && t !== wildcardType && !isErrorType(t)) { if (!type.declaration.nameType) { - if (isArrayType(t)) { + var constraint = void 0; + if (isArrayType(t) || t.flags & 1 && findResolutionCycleStartIndex(typeVariable, 4) < 0 && + (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, ts.or(isArrayType, isTupleType))) { return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); } if (isGenericTupleType(t)) { @@ -52480,10 +52632,11 @@ var ts; traceUnionsOrIntersectionsTooLarge(source, target); var result = 0; var saveErrorInfo = captureErrorCalculationState(); - if (source.flags & 3145728 || target.flags & 3145728) { - result = getConstituentCount(source) * getConstituentCount(target) >= 4 ? - recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8, recursionFlags) : - structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8); + if ((source.flags & 1048576 || target.flags & 1048576) && getConstituentCount(source) * getConstituentCount(target) < 4) { + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8); + } + else if (source.flags & 3145728 || target.flags & 3145728) { + result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8, recursionFlags); } if (!result && !(source.flags & 1048576) && (source.flags & (469499904) || target.flags & 469499904)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { @@ -52863,19 +53016,19 @@ var ts; var maybeStart = maybeCount; maybeKeys[maybeCount] = id; maybeCount++; + var saveExpandingFlags = expandingFlags; if (recursionFlags & 1) { sourceStack[sourceDepth] = source; sourceDepth++; + if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, sourceDepth)) + expandingFlags |= 1; } if (recursionFlags & 2) { targetStack[targetDepth] = target; targetDepth++; + if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, targetDepth)) + expandingFlags |= 2; } - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, sourceDepth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, targetDepth)) - expandingFlags |= 2; var originalHandler; var propagatingVarianceFlags = 0; if (outofbandVarianceMarkerHandler) { @@ -52899,13 +53052,13 @@ var ts; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } - expandingFlags = saveExpandingFlags; if (recursionFlags & 1) { sourceDepth--; } if (recursionFlags & 2) { targetDepth--; } + expandingFlags = saveExpandingFlags; if (result) { if (result === -1 || (sourceDepth === 0 && targetDepth === 0)) { if (result === -1 || result === 3) { @@ -53093,7 +53246,7 @@ var ts; originalErrorInfo = undefined; } } - else if (isGenericMappedType(target)) { + else if (isGenericMappedType(target) && relation !== identityRelation) { var keysRemapped = !!target.declaration.nameType; var templateType = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); @@ -53136,26 +53289,21 @@ var ts; } } else if (target.flags & 16777216) { - var c = target; - var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); - var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); - var distributionMapper = void 0; - var checkVar = getActualTypeVariable(c.root.checkType); - if (c.root.isDistributive && checkVar.flags & 262144) { - var newParam = cloneTypeParameter(checkVar); - distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); - newParam.mapper = distributionMapper; - } - var expanding = isDeeplyNestedType(target, targetStack, targetDepth); - var localResult = expanding ? 3 : undefined; - if (skipTrue || expanding || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), 2, false))) { - if (!skipFalse && !expanding) { - localResult = (localResult || 3) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), 2, false); - } - } - if (localResult) { + if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { resetErrorInfo(saveErrorInfo); - return localResult; + return 3; + } + var c = target; + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) { + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); + if (result = skipTrue ? -1 : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2, false)) { + result &= skipFalse ? -1 : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2, false); + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + } } } else if (target.flags & 134217728) { @@ -53165,8 +53313,7 @@ var ts; } instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_9 = inferTypesFromTemplateLiteralType(source, target); - if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1; } } @@ -53220,26 +53367,28 @@ var ts; } } else if (source.flags & 16777216) { + if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { + resetErrorInfo(saveErrorInfo); + return 3; + } if (target.flags & 16777216) { - if (!isDeeplyNestedType(source, sourceStack, sourceDepth) && !isDeeplyNestedType(target, targetStack, targetDepth)) { - var sourceParams = source.root.inferTypeParameters; - var sourceExtends = source.extendsType; - var mapper = void 0; - if (sourceParams) { - var ctx = createInferenceContext(sourceParams, undefined, 0, isRelatedToWorker); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 | 1024); - sourceExtends = instantiateType(sourceExtends, ctx.mapper); - mapper = ctx.mapper; + var sourceParams = source.root.inferTypeParameters; + var sourceExtends = source.extendsType; + var mapper = void 0; + if (sourceParams) { + var ctx = createInferenceContext(sourceParams, undefined, 0, isRelatedToWorker); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 | 1024); + sourceExtends = instantiateType(sourceExtends, ctx.mapper); + mapper = ctx.mapper; + } + if (isTypeIdenticalTo(sourceExtends, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType, 3) || isRelatedTo(target.checkType, source.checkType, 3))) { + if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3, reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3, reportErrors); } - if (isTypeIdenticalTo(sourceExtends, target.extendsType) && - (isRelatedTo(source.checkType, target.checkType, 3) || isRelatedTo(target.checkType, source.checkType, 3))) { - if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3, reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -53252,13 +53401,11 @@ var ts; } } } - if (!isDeeplyNestedType(source, sourceStack, sourceDepth)) { - var defaultConstraint = getDefaultConstraintOfConditionalType(source); - if (defaultConstraint) { - if (result = isRelatedTo(defaultConstraint, target, 1, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, 1, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -53326,9 +53473,9 @@ var ts; if (source.flags & (524288 | 2097152) && target.flags & 1048576) { var objectOnlyTarget = extractTypesOfKind(target, 524288 | 2097152 | 33554432); if (objectOnlyTarget.flags & 1048576) { - var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_10) { - return result_10; + var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_9) { + return result_9; } } } @@ -53375,13 +53522,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_11; + var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, 3, reportErrors)) { + if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3, reportErrors); + return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3, reportErrors); } } } @@ -54202,14 +54349,15 @@ var ts; return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5) { + function isDeeplyNestedType(type, stack, depth, maxDepth) { + if (maxDepth === void 0) { maxDepth = 5; } + if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; for (var i = 0; i < depth; i++) { if (getRecursionIdentity(stack[i]) === identity_1) { count++; - if (count >= 5) { + if (count >= maxDepth) { return true; } } @@ -54851,7 +54999,8 @@ var ts; (resolveName(param, param.name.escapedText, 788968, undefined, param.name.escapedText, true) || param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { var newName = "arg" + param.parent.parameters.indexOf(param); - errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + var typeName = ts.declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); return; } diagnostic = declaration.dotDotDotToken ? @@ -55214,6 +55363,10 @@ var ts; inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : undefined; } + function isTypeMatchedByTemplateLiteralType(source, target) { + var inferences = inferTypesFromTemplateLiteralType(source, target); + return !!inferences && ts.every(inferences, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); }); + } function getStringLikeTypeForType(type) { return type.flags & (1 | 402653316) ? type : getTemplateLiteralType(["", ""], [type]); } @@ -55859,15 +56012,14 @@ var ts; var inferredType = void 0; var signature = context.signature; if (signature) { - var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + var inferredCovariantType_1 = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - var inferredContravariantType = getContravariantInference(inference); - inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072) && - isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? - inferredCovariantType : inferredContravariantType; + inferredType = inferredCovariantType_1 && !(inferredCovariantType_1.flags & 131072) && + ts.some(inference.contraCandidates, function (t) { return isTypeSubtypeOf(inferredCovariantType_1, t); }) ? + inferredCovariantType_1 : getContravariantInference(inference); } - else if (inferredCovariantType) { - inferredType = inferredCovariantType; + else if (inferredCovariantType_1) { + inferredType = inferredCovariantType_1; } else if (context.flags & 1) { inferredType = silentNeverType; @@ -55958,7 +56110,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 111551 | 1048576, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), false, true) || unknownSymbol; + resolveName(node, node.escapedText, 111551 | 1048576, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), false) || unknownSymbol; } return links.resolvedSymbol; } @@ -55968,8 +56120,10 @@ var ts; function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 79: - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + if (!ts.isThisInTypeQuery(node)) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + } case 108: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); case 229: @@ -56141,7 +56295,8 @@ var ts; } function getKeyPropertyName(unionType) { var types = unionType.types; - if (types.length < 10 || ts.getObjectFlags(unionType) & 65536) { + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 || + ts.countWhere(types, function (t) { return !!(t.flags & (524288 | 58982400)); }) < 10) { return undefined; } if (unionType.keyPropertyName === undefined) { @@ -56170,7 +56325,7 @@ var ts; var keyPropertyName = getKeyPropertyName(unionType); var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 294 && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); - var propType = propNode && getTypeOfExpression(propNode.initializer); + var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } function isOrContainsMatchingReference(source, target) { @@ -56567,7 +56722,7 @@ var ts; mapType(type, mapper); } function getConstituentCount(type) { - return type.flags & 3145728 ? type.types.length : 1; + return type.flags & 1048576 ? type.types.length : 1; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -57853,7 +58008,7 @@ var ts; return parent.kind === 205 || parent.kind === 207 && parent.expression === node || parent.kind === 206 && parent.expression === node && - !(isGenericTypeWithoutNullableConstraint(type) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); + !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { return !!(type.flags & 465829888 && getBaseConstraintOrType(type).flags & (98304 | 1048576)); @@ -58946,7 +59101,7 @@ var ts; return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 294 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function getApparentTypeOfContextualType(node, contextFlags) { var contextualType = ts.isObjectLiteralMethod(node) ? @@ -59401,6 +59556,10 @@ var ts; function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { + if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101) { + return links.resolvedType = errorType; + } links.resolvedType = checkExpression(node.expression); if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) { var container = ts.getEnclosingBlockScopeContainer(node.parent.parent); @@ -60658,7 +60817,7 @@ var ts; if (relatedInfo) { ts.addRelatedInfo(resultDiagnostic, relatedInfo); } - addErrorOrSuggestion(!isUncheckedJS, resultDiagnostic); + addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && @@ -60728,7 +60887,19 @@ var ts; 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); + if (symbol) + return symbol; + var candidates; + if (symbols === globals) { + var primitives = ts.mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], function (s) { return symbols.has((s.charAt(0).toUpperCase() + s.slice(1))) + ? createSymbol(524288, s) + : undefined; }); + candidates = primitives.concat(ts.arrayFrom(symbols.values())); + } + else { + candidates = ts.arrayFrom(symbols.values()); + } + return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), candidates, meaning); }); return result; } @@ -62538,11 +62709,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true, false); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } } return createPromiseReturnType(node, anyType); } + function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152, "default"); + newSymbol.parent = originalSymbol; + newSymbol.nameType = getStringLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default", newSymbol); + return createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + } + function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { + var hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier); + if (hasDefaultOnly && type && !isErrorType(type)) { + var synthType = type; + if (!synthType.defaultOnlyType) { + var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_4; + } + return synthType.defaultOnlyType; + } + return undefined; + } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { var _a; if (allowSyntheticDefaultImports && type && !isErrorType(type)) { @@ -62551,14 +62744,8 @@ var ts; var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false, moduleSpecifier); if (hasSyntheticDefault) { - var memberTable = ts.createSymbolTable(); - var newSymbol = createSymbol(2097152, "default"); - newSymbol.parent = originalSymbol; - newSymbol.nameType = getStringLiteralType("default"); - newSymbol.target = resolveSymbol(symbol); - memberTable.set("default", newSymbol); var anonymousSymbol = createSymbol(2048, "__type"); - var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); anonymousSymbol.type = defaultContainingObject; synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0, false) : defaultContainingObject; } @@ -63205,11 +63392,11 @@ var ts; var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node, false); var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; - if (type_4.flags & 3) { + var type_5 = getBaseConstraintOfType(operandType) || operandType; + if (type_5.flags & 3) { return (556800 & notEqualFacts_1) === 556800; } - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072); + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -65508,6 +65695,8 @@ var ts; if (!typeReferenceNode) return undefined; var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + if (!typeParameters) + return undefined; var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -65518,7 +65707,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); + checkIndexConstraints(type, type.symbol); checkTypeForDuplicateIndexSignatures(node); checkObjectTypeForDuplicateDeclarations(node); } @@ -65610,6 +65799,7 @@ var ts; checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { + checkGrammarMappedType(node); checkSourceElement(node.typeParameter); checkSourceElement(node.nameType); checkSourceElement(node.type); @@ -65626,6 +65816,12 @@ var ts; checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); } } + function checkGrammarMappedType(node) { + var _a; + if ((_a = node.members) === null || _a === void 0 ? void 0 : _a.length) { + return grammarErrorOnNode(node.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + } function checkThisType(node) { getTypeFromThisTypeNode(node); } @@ -65959,12 +66155,12 @@ var ts; case 264: case 267: case 266: - var result_12 = 0; + var result_11 = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { - result_12 |= getDeclarationSpaces(d); + result_11 |= getDeclarationSpaces(d); }); - return result_12; + return result_11; case 253: case 202: case 255: @@ -67962,7 +68158,7 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type, isStaticIndex) { + function checkIndexConstraints(type, symbol, isStaticIndex) { var indexInfos = getIndexInfosOfType(type); if (indexInfos.length === 0) { return; @@ -67973,13 +68169,13 @@ var ts; checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576, true), getNonMissingTypeOfSymbol(prop)); } } - var typeDeclaration = type.symbol.valueDeclaration; + var typeDeclaration = symbol.valueDeclaration; if (typeDeclaration && ts.isClassLike(typeDeclaration)) { for (var _b = 0, _c = typeDeclaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (!ts.isStatic(member) && !hasBindableName(member)) { - var symbol = getSymbolOfNode(member); - checkIndexConstraintForProperty(type, symbol, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol)); + var symbol_3 = getSymbolOfNode(member); + checkIndexConstraintForProperty(type, symbol_3, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol_3)); } } } @@ -68235,7 +68431,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); + checkMembersForOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -68264,14 +68460,13 @@ var ts; } } if (produceDiagnostics) { - checkIndexConstraints(type); - checkIndexConstraints(staticType, true); + checkIndexConstraints(type, symbol); + checkIndexConstraints(staticType, symbol, true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { - var nodeInAmbientContext = !!(node.flags & 8388608); + function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) { var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; @@ -68283,46 +68478,57 @@ var ts; if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { - checkClassMember(param, true); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, true); } }); } - checkClassMember(member); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, false); }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; _loop_29(member); } - function checkClassMember(member, memberIsParameterProperty) { - var hasOverride = ts.hasOverrideModifier(member); - var hasStatic = ts.isStatic(member); - var isJs = ts.isInJSFile(member); - if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { - var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); - if (!declaredProp) { - return; - } - var thisType = hasStatic ? staticType : typeWithThis; - var baseType = hasStatic ? baseStaticType : baseWithThis; - var prop = getPropertyOfType(thisType, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); - var baseClassName = typeToString(baseWithThis); - if (prop && !baseProp && hasOverride) { - var suggestion = getSuggestedSymbolForNonexistentClassMember(ts.symbolName(declaredProp), baseType); + } + function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { + if (reportErrors === void 0) { reportErrors = true; } + var declaredProp = member.name + && getSymbolAtLocation(member.name) + || getSymbolAtLocation(member); + if (!declaredProp) { + return 0; + } + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, ts.hasOverrideModifier(member), ts.hasAbstractModifier(member), ts.isStatic(member), memberIsParameterProperty, ts.symbolName(declaredProp), reportErrors ? member : undefined); + } + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { + var isJs = ts.isInJSFile(node); + var nodeInAmbientContext = !!(node.flags & 8388608); + if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { + var memberEscapedName = ts.escapeLeadingUnderscores(memberName); + var thisType = memberIsStatic ? staticType : typeWithThis; + var baseType = memberIsStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, memberEscapedName); + var baseProp = getPropertyOfType(baseType, memberEscapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && memberHasOverrideModifier) { + if (errorNode) { + var suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); suggestion ? - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } - else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { - var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); - if (hasOverride) { - return; - } - if (!baseHasAbstract) { + return 2; + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); + if (memberHasOverrideModifier) { + return 0; + } + if (!baseHasAbstract) { + if (errorNode) { var diag = memberIsParameterProperty ? isJs ? ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : @@ -68330,20 +68536,28 @@ var ts; isJs ? ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; - error(member, diag, baseClassName); + error(errorNode, diag, baseClassName); } - else if (ts.hasAbstractModifier(member) && baseHasAbstract) { - error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + return 1; + } + else if (memberHasAbstractModifier && baseHasAbstract) { + if (errorNode) { + error(errorNode, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); } + return 1; } } - else if (hasOverride) { + } + else if (memberHasOverrideModifier) { + if (errorNode) { var className = typeToString(type); - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } + return 2; } + return 0; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; @@ -68383,6 +68597,24 @@ var ts; } } } + function getMemberOverrideModifierStatus(node, member) { + if (!member.name) { + return 0; + } + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var memberHasOverrideModifier = member.parent + ? ts.hasOverrideModifier(member) + : ts.hasSyntacticModifier(member, 16384); + var memberName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name)); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, ts.hasAbstractModifier(member), ts.isStatic(member), false, memberName); + } function getTargetSymbol(s) { return ts.getCheckFlags(s) & 1 ? s.target : s; } @@ -68616,7 +68848,7 @@ var ts; var baseType = _a[_i]; checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); } - checkIndexConstraints(type); + checkIndexConstraints(type, symbol); } } checkObjectTypeForDuplicateDeclarations(node); @@ -72442,6 +72674,9 @@ var ts; } } function checkGrammarProperty(node) { + if (ts.isComputedPropertyName(node.name) && ts.isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101) { + return grammarErrorOnNode(node.parent.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } if (ts.isClassLike(node.parent)) { if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); @@ -72461,7 +72696,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 181) { + else if (ts.isTypeLiteralNode(node.parent)) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -73052,7 +73287,7 @@ var ts; return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); case 194: ts.Debug.type(node); - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 195: ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); @@ -79057,11 +79292,11 @@ var ts; currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } - function getJsxFactoryCalleePrimitive(childrenLength) { - return compilerOptions.jsx === 5 ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx"; + function getJsxFactoryCalleePrimitive(isStaticChildren) { + return compilerOptions.jsx === 5 ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx"; } - function getJsxFactoryCallee(childrenLength) { - var type = getJsxFactoryCalleePrimitive(childrenLength); + function getJsxFactoryCallee(isStaticChildren) { + var type = getJsxFactoryCalleePrimitive(isStaticChildren); return getImplicitImportForName(type); } function getImplicitJsxFragmentReference() { @@ -79195,52 +79430,36 @@ var ts; return tagTransform(node.openingFragment, node.children, isChild, node); } function convertJsxChildrenToChildrenPropObject(children) { + var prop = convertJsxChildrenToChildrenPropAssignment(children); + return prop && factory.createObjectLiteralExpression([prop]); + } + function convertJsxChildrenToChildrenPropAssignment(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); - if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) - ]); + if (ts.length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) { + var result_12 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_12 && factory.createPropertyAssignment("children", result_12); } var result = ts.mapDefined(children, transformJsxChildToExpression); - return !result.length ? undefined : factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) - ]); + return ts.length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined; } function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; + var childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined; var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; }); var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties; - var segments = []; - if (attrs.length) { - segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - segments.unshift(factory.createObjectLiteralExpression()); - } - } - if (children && children.length) { - var result = convertJsxChildrenToChildrenPropObject(children); - if (result) { - segments.push(result); - } - } - if (segments.length === 0) { - objectProperties = factory.createObjectLiteralExpression([]); - } - else { - objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments); - } - return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location); + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : + factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : ts.emptyArray); + return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || ts.emptyArray, isChild, location); } - function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) { + function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { + var _a; + var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); + var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; if (compilerOptions.jsx === 5) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { - args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse()); + args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos); args.push(factory.createObjectLiteralExpression([ factory.createPropertyAssignment("fileName", getCurrentFileNameExpression()), @@ -79250,7 +79469,7 @@ var ts; args.push(factory.createThis()); } } - var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), undefined, args), location); + var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), undefined, args), location); if (isChild) { ts.startOnNewLine(element); } @@ -79258,31 +79477,9 @@ var ts; } function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; var attrs = node.attributes.properties; - if (attrs.length === 0) { - objectProperties = factory.createNull(); - } - else { - var target = ts.getEmitScriptTarget(compilerOptions); - if (target && target >= 5) { - objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { - return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); - }))); - } - else { - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - segments.unshift(factory.createObjectLiteralExpression()); - } - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); - } - } - } + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs) : + factory.createNull(); var callee = currentFileState.importSpecifier === undefined ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, node) : getImplicitImportForName("createElement"); @@ -79300,7 +79497,7 @@ var ts; childrenProps = result; } } - return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location); + return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), undefined, children, isChild, location); } function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); @@ -79312,6 +79509,32 @@ var ts; function transformJsxSpreadAttributeToSpreadAssignment(node) { return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); } + function transformJsxAttributesToObjectProps(attrs, children) { + var target = ts.getEmitScriptTarget(compilerOptions); + return target && target >= 5 ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : + transformJsxAttributesToExpression(attrs, children); + } + function transformJsxAttributesToProps(attrs, children) { + var props = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return ts.map(attrs, function (attr) { return isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr); }); + })); + if (children) { + props.push(children); + } + return props; + } + function transformJsxAttributesToExpression(attrs, children) { + var expressions = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + expressions.unshift(factory.createObjectLiteralExpression()); + } + if (children) { + expressions.push(factory.createObjectLiteralExpression([children])); + } + return ts.singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -81569,33 +81792,16 @@ var ts; return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All); } function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - var expression = ts.reduceLeft(expressions, factory.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - function shouldAddTemplateHead(node) { - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(factory.createStringLiteral(node.head.text)); - } - function addTemplateSpans(expressions, node) { + var expression = factory.createStringLiteral(node.head.text); for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { var span = _a[_i]; - expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); - if (span.literal.text.length !== 0) { - expressions.push(factory.createStringLiteral(span.literal.text)); + var args = [ts.visitNode(span.expression, visitor, ts.isExpression)]; + if (span.literal.text.length > 0) { + args.push(factory.createStringLiteral(span.literal.text)); } + expression = factory.createCallExpression(factory.createPropertyAccessExpression(expression, "concat"), undefined, args); } + return ts.setTextRange(expression, node); } function visitSuperKeyword(isExpressionOfCall) { return hierarchyFacts & 8 @@ -88651,7 +88857,14 @@ var ts; onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); currentParenthesizerRule = undefined; } - function pipelineEmitWithHintWorker(hint, node) { + function pipelineEmitWithHintWorker(hint, node, allowSnippets) { + if (allowSnippets === void 0) { allowSnippets = true; } + if (allowSnippets) { + var snippet = ts.getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } if (hint === 0) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2) @@ -89200,6 +89413,24 @@ var ts; bundleFileInfo.sections.push(section); } } + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1: + emitPlaceholder(hint, node, snippet); + break; + case 0: + emitTabStop(snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite("${" + snippet.order + ":"); + pipelineEmitWithHintWorker(hint, node, false); + nonEscapingWrite("}"); + } + function emitTabStop(snippet) { + nonEscapingWrite("$" + snippet.order); + } function emitIdentifier(node) { var writeText = node.symbol ? writeSymbol : write; writeText(getTextOfNode(node, false), node.symbol); @@ -91309,6 +91540,14 @@ var ts; function writeProperty(s) { writer.writeProperty(s); } + function nonEscapingWrite(s) { + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } + else { + writer.write(s); + } + } function writeLine(count) { if (count === void 0) { count = 1; } for (var i = 0; i < count; i++) { @@ -92393,7 +92632,7 @@ var ts; var rootResult = tryReadDirectory(rootDir, rootDirPath); var rootSymLinkResult; if (rootResult !== undefined) { - return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -93271,7 +93510,7 @@ var ts; break; case ts.FileIncludeKind.TypeReferenceDirective: (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end); - packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), getModeForResolutionAtIndex(file, index))) === null || _g === void 0 ? void 0 : _g.packageId; + packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId; break; case ts.FileIncludeKind.LibReferenceDirective: (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end); @@ -93738,15 +93977,15 @@ var ts; } var oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName); if (oldSourceFile !== file && file.resolvedModules) { - var result_14 = []; + var result_13 = []; var i = 0; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i)); i++; - result_14.push(resolvedModule); + result_13.push(resolvedModule); } - return result_14; + return result_13; } var unknownModuleNames; var result; @@ -93964,8 +94203,8 @@ var ts; } var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); }); var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile); - var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); - if (typeReferenceEesolutionsChanged) { + var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); + if (typeReferenceResolutionsChanged) { structureIsReused = 1; newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions); } @@ -95104,6 +95343,21 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { + var isNightly = ts.stringContains(ts.version, "-dev"); + if (!isNightly) { + if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); + } + else if (ts.getEmitModuleKind(options) === ts.ModuleKind.NodeNext) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext"); + } + } if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } @@ -95247,7 +95501,9 @@ var ts; } } if (options.resolveJsonModule) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } else if (!ts.hasJsonModuleEmitEnabled(options)) { @@ -95559,8 +95815,8 @@ var ts; function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(true, option1, option2, message, option1, option2, option3); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(false, option1, undefined, message, arg0); + function createOptionValueDiagnostic(option1, message, arg0, arg1) { + createDiagnosticForOption(false, option1, undefined, message, arg0, arg1); } function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); @@ -97424,6 +97680,9 @@ var ts; else { resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile); perDirectoryResolution.set(name, mode, resolution); + if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { + resolutionHost.onDiscoveredSymlink(); + } } resolutionsInFile.set(name, mode, resolution); watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); @@ -97841,6 +98100,11 @@ var ts; } } ts.createResolutionCache = createResolutionCache; + function resolutionIsSymlink(resolution) { + var _a, _b; + return !!(((_a = resolution.resolvedModule) === null || _a === void 0 ? void 0 : _a.originalPath) || + ((_b = resolution.resolvedTypeReferenceDirective) === null || _b === void 0 ? void 0 : _b.originalPath)); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -98076,9 +98340,9 @@ var ts; var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_14 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_14) + return result_14; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -98097,10 +98361,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_15 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; - if (result_16) - return result_16; + if (result_15) + return result_15; } }); }); @@ -98356,13 +98620,15 @@ var ts; var moduleFileToTry = path; if (host.fileExists(packageJsonPath)) { var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; - if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; - return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); - } - if (packageJsonContent.exports) { - return { moduleFileToTry: path, blockedByExports: true }; + if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + if (fromExports) { + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); + } + if (packageJsonContent.exports) { + return { moduleFileToTry: path, blockedByExports: true }; + } } var versionPaths = packageJsonContent.typesVersions ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -99316,6 +99582,9 @@ var ts; sourceFilesCache.set(path, false); } } + if (sourceFile) { + sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); + } return sourceFile; } return hostSourceFile.sourceFile; @@ -100194,11 +100463,11 @@ var ts; (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [state.host.realpath ? toPath(state, state.host.realpath(path)) : path, data]; - })); if (state.watch) { + state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { + var path = _a[0], data = _a[1]; + return [state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data]; + })); state.builderPrograms.set(projectPath, program); } step++; diff --git a/lib/tsserver.js b/lib/tsserver.js index 873d71444b807..f0694f53a07e1 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -22,7 +22,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -100,7 +100,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.5.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -129,21 +129,24 @@ var ts; return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; - })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { + })(NativeCollections || (NativeCollections = {})); + /* @internal */ + ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); + /* @internal */ + ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); + /* @internal */ function getCollectionImplementation(name, nativeFactory, shimFactory) { var _a; // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it. - var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator); + var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); if (constructor) return constructor; throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation."); } - ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); - ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { function getIterator(iterable) { if (iterable) { if (isArray(iterable)) @@ -2548,6 +2551,10 @@ var ts; return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } Debug.formatSyntaxKind = formatSyntaxKind; + function formatSnippetKind(kind) { + return formatEnum(kind, ts.SnippetKind, /*isFlags*/ false); + } + Debug.formatSnippetKind = formatSnippetKind; function formatNodeFlags(flags) { return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true); } @@ -4464,6 +4471,13 @@ var ts; ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ + var MemberOverrideStatus; + (function (MemberOverrideStatus) { + MemberOverrideStatus[MemberOverrideStatus["Ok"] = 0] = "Ok"; + MemberOverrideStatus[MemberOverrideStatus["NeedsOverride"] = 1] = "NeedsOverride"; + MemberOverrideStatus[MemberOverrideStatus["HasInvalidOverride"] = 2] = "HasInvalidOverride"; + })(MemberOverrideStatus = ts.MemberOverrideStatus || (ts.MemberOverrideStatus = {})); + /* @internal */ var UnionReduction; (function (UnionReduction) { UnionReduction[UnionReduction["None"] = 0] = "None"; @@ -4859,8 +4873,6 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable"; - /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 468598819] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask"; @@ -4873,6 +4885,10 @@ var ts; TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["IncludesInstantiable"] = 33554432] = "IncludesInstantiable"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check @@ -5112,7 +5128,7 @@ var ts; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - // Starting with node12, node's module resolver has significant departures from tranditional cjs resolution + // Starting with node12, node's module resolver has significant departures from traditional cjs resolution // to better support ecmascript modules and their use within node - more features are still being added, so // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12` // version-anchored resolution target @@ -5445,6 +5461,15 @@ var ts; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax + /* @internal */ + var SnippetKind; + (function (SnippetKind) { + SnippetKind[SnippetKind["TabStop"] = 0] = "TabStop"; + SnippetKind[SnippetKind["Placeholder"] = 1] = "Placeholder"; + SnippetKind[SnippetKind["Choice"] = 2] = "Choice"; + SnippetKind[SnippetKind["Variable"] = 3] = "Variable"; + })(SnippetKind = ts.SnippetKind || (ts.SnippetKind = {})); var EmitFlags; (function (EmitFlags) { EmitFlags[EmitFlags["None"] = 0] = "None"; @@ -7738,7 +7763,7 @@ var ts; } } function readDirectory(path, extensions, excludes, includes, depth) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve @@ -7823,6 +7848,11 @@ var ts; } return sys; })(); + /*@internal*/ + function setSys(s) { + ts.sys = s; + } + ts.setSys = setSys; if (ts.sys && ts.sys.getEnvironmentVariable) { setCustomPollingValues(ts.sys); ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) @@ -8133,6 +8163,7 @@ var ts; Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."), Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), + _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8674,6 +8705,9 @@ var ts; Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), 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}'."), @@ -8780,6 +8814,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), 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}'."), @@ -9332,6 +9367,8 @@ var ts; If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."), + A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."), + JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."), 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_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."), @@ -9387,7 +9424,7 @@ var ts; Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."), This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), @@ -9435,6 +9472,7 @@ var ts; Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"), Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), + Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), 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_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -9449,7 +9487,7 @@ var ts; 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"), + Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"), Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), @@ -19628,6 +19666,8 @@ var ts; case ts.ModuleKind.ES2020: case ts.ModuleKind.ES2022: case ts.ModuleKind.ESNext: + case ts.ModuleKind.Node12: + case ts.ModuleKind.NodeNext: return true; default: return false; @@ -19992,7 +20032,7 @@ var ts; } ts.getRegexFromPattern = getRegexFromPattern; /** @param path directory of the tsconfig.json */ - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -20006,9 +20046,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - if (directoryExists(basePath)) { - visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); - } + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -20113,10 +20151,14 @@ var ts; var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { case ".js" /* Js */: + case ".cjs" /* Cjs */: + case ".mjs" /* Mjs */: return 1 /* JS */; case ".jsx" /* Jsx */: return 2 /* JSX */; case ".ts" /* Ts */: + case ".cts" /* Cts */: + case ".mts" /* Mts */: return 3 /* TS */; case ".tsx" /* Tsx */: return 4 /* TSX */; @@ -20735,6 +20777,10 @@ var ts; return node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; + function escapeSnippetText(text) { + return text.replace(/\$/gm, "\\$"); + } + ts.escapeSnippetText = escapeSnippetText; })(ts || (ts = {})); /* @internal */ var ts; @@ -22892,24 +22938,26 @@ var ts; : node; } // @api - function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { + function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { var node = createBaseNode(194 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; node.questionToken = questionToken; node.type = type; + node.members = members && createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api - function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) { + function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) { return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type - ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node) + || node.members !== members + ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } // @api @@ -26936,6 +26984,25 @@ var ts; } } ts.moveEmitHelpers = moveEmitHelpers; + /** + * Gets the SnippetElement of a node. + */ + /* @internal */ + function getSnippetElement(node) { + var _a; + return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement; + } + ts.getSnippetElement = getSnippetElement; + /** + * Sets the SnippetElement of a node. + */ + /* @internal */ + function setSnippetElement(node, snippet) { + var emitNode = getOrCreateEmitNode(node); + emitNode.snippetElement = snippet; + return node; + } + ts.setSnippetElement = setSnippetElement; /* @internal */ function ignoreSourceNewlines(node) { getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */; @@ -29782,7 +29849,8 @@ var ts; visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) || + visitNodes(cbNode, cbNodes, node.members); case 195 /* LiteralType */: return visitNode(cbNode, node.literal); case 196 /* NamedTupleMember */: @@ -31916,7 +31984,10 @@ var ts; case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected); case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected); case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); - case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); + case 16 /* Parameters */: + return ts.isKeyword(token()) + ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_parameter_name, ts.tokenToString(token())) + : parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected); case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected); case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected); @@ -32672,8 +32743,9 @@ var ts; } var type = parseTypeAnnotation(); parseSemicolon(); + var members = parseList(4 /* TypeMembers */, parseTypeMember); parseExpected(19 /* CloseBraceToken */); - return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos); + return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } function parseTupleElementType() { var pos = getNodePos(); @@ -35960,16 +36032,21 @@ var ts; var pos = getNodePos(); parseExpected(129 /* AssertKeyword */); var openBracePosition = scanner.getTokenPos(); - parseExpected(18 /* OpenBraceToken */); - var multiLine = scanner.hasPrecedingLineBreak(); - var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); - if (!parseExpected(19 /* CloseBraceToken */)) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { - ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + if (parseExpected(18 /* OpenBraceToken */)) { + var multiLine = scanner.hasPrecedingLineBreak(); + var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); + if (!parseExpected(19 /* CloseBraceToken */)) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { + ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + } } + return finishNode(factory.createAssertClause(elements, multiLine), pos); + } + else { + var elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false); + return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos); } - return finishNode(factory.createAssertClause(elements, multiLine), pos); } function tokenAfterImportDefinitelyProducesImportDeclaration() { return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */; @@ -36864,8 +36941,9 @@ var ts; return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); - var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */ + || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference(); var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } @@ -37954,7 +38032,7 @@ var ts; var ts; (function (ts) { /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1 /* Preserve */, "react-native": 3 /* ReactNative */, @@ -38091,6 +38169,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: "false", }, { name: "excludeDirectories", @@ -38126,11 +38205,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, + defaultValueDescription: "false", }, { name: "help", shortName: "?", - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "watch", @@ -38140,6 +38221,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, + defaultValueDescription: "false", }, { name: "preserveWatchOutput", @@ -38147,7 +38229,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "listFiles", @@ -38160,7 +38242,8 @@ var ts; name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, - description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included + description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: "false", }, { name: "listEmittedFiles", @@ -38231,7 +38314,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, - description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it + description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: "false", }, { name: "locale", @@ -38276,6 +38360,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, + defaultValueDescription: "false", }, { name: "version", @@ -38284,6 +38369,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: "false", }, { name: "init", @@ -38291,6 +38377,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: "false", }, { name: "project", @@ -38308,7 +38395,8 @@ var ts; shortName: "b", showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: "false", }, { name: "showConfig", @@ -38316,7 +38404,8 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, - description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: "false", }, { name: "listFilesOnly", @@ -38325,7 +38414,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, isCommandLineOnly: true, - description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: "false", }, // Basic ts.targetOptionDeclaration, @@ -38445,7 +38535,6 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, transpileOptionValue: undefined, - defaultValueDescription: "n/a" }, { name: "outDir", @@ -38456,7 +38545,6 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files, - defaultValueDescription: "n/a" }, { name: "rootDir", @@ -38613,6 +38701,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: "false", }, { name: "alwaysStrict", @@ -38645,7 +38734,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined + description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: "false", }, { name: "noImplicitReturns", @@ -38661,21 +38751,24 @@ var ts; affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements + description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: "false", }, { name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Include_undefined_in_index_signature_results + description: ts.Diagnostics.Include_undefined_in_index_signature_results, + defaultValueDescription: "false", }, { name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: "false", }, { name: "noPropertyAccessFromIndexSignature", @@ -38691,6 +38784,8 @@ var ts; type: new ts.Map(ts.getEntries({ node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, + node12: ts.ModuleResolutionKind.Node12, + nodenext: ts.ModuleResolutionKind.NodeNext, })), affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, @@ -38782,7 +38877,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "allowUmdGlobalAccess", @@ -38831,7 +38926,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators + description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, + defaultValueDescription: "false", }, { name: "emitDecoratorMetadata", @@ -38839,7 +38935,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files + description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: "false", }, // Advanced { @@ -38882,7 +38979,6 @@ var ts; category: ts.Diagnostics.Backwards_Compatibility, paramType: ts.Diagnostics.FILE, transpileOptionValue: undefined, - defaultValueDescription: "n/a", description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead, }, { @@ -38963,6 +39059,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: "false", }, { name: "disableSizeLimit", @@ -38977,21 +39074,24 @@ var ts; type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects + description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: "false", }, { name: "disableSolutionSearching", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing + description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: "false", }, { name: "disableReferencedProjectLoad", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript + description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: "false", }, { name: "noImplicitUseStrict", @@ -39024,7 +39124,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "declarationDir", @@ -39035,7 +39135,6 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files, - defaultValueDescription: "n/a" }, { name: "skipLibCheck", @@ -39117,6 +39216,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: "false", }, { name: "keyofStringsOnly", @@ -39164,27 +39264,31 @@ var ts; shortName: "v", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "dry", shortName: "d", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "force", shortName: "f", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", } ]; /* @internal */ @@ -39197,10 +39301,12 @@ var ts; */ name: "enableAutoDiscovery", type: "boolean", + defaultValueDescription: "false", }, { name: "enable", type: "boolean", + defaultValueDescription: "false", }, { name: "include", @@ -39221,6 +39327,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", + defaultValueDescription: "false", }, ]; /*@internal*/ @@ -42493,11 +42600,15 @@ var ts; if (!scope || !scope.packageJsonContent.exports) { return undefined; } + if (typeof scope.packageJsonContent.name !== "string") { + return undefined; + } var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry - if (scope.packageJsonContent.name !== parts[1]) { + var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } - var trailingParts = parts.slice(2); + var trailingParts = parts.slice(nameParts.length); return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : "." + ts.directorySeparator + trailingParts.join(ts.directorySeparator), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { @@ -45636,6 +45747,7 @@ var ts; case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: case 172 /* SetAccessor */: + case 169 /* ClassStaticBlockDeclaration */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -47016,6 +47128,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isPropertyAccessible: isPropertyAccessible, getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration, + getMemberOverrideModifierStatus: getMemberOverrideModifierStatus, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -47259,6 +47372,21 @@ var ts; var enumRelation = new ts.Map(); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + // Extensions suggested for path imports when module resolution is node12 or higher. + // The first element of each tuple is the extension a file has. + // The second element of each tuple is the extension that should be used in a path import. + // e.g. if we want to import file `foo.mts`, we should write `import {} from "./foo.mjs". + var suggestedExtensions = [ + [".mts", ".mjs"], + [".ts", ".js"], + [".cts", ".cjs"], + [".mjs", ".mjs"], + [".js", ".js"], + [".cjs", ".cjs"], + [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], + [".jsx", ".jsx"], + [".json", ".json"], + ]; initializeTypeChecker(); return checker; function getJsxNamespace(location) { @@ -47975,11 +48103,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, issueSuggestions) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, issueSuggestions); + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, issueSuggestions) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { var _a, _b, _c; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; @@ -48306,7 +48434,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (issueSuggestions && suggestionCount < maximumSuggestionCount) { + if (suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -48315,7 +48443,9 @@ var ts; if (suggestion) { var suggestionName = symbolToString(suggestion); var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); - var message = isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; + var message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 + : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 + : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { @@ -48760,6 +48890,10 @@ var ts; function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === ts.ModuleKind.ESNext && targetMode === ts.ModuleKind.CommonJS; } + function isOnlyImportedAsDefault(usage) { + var usageMode = getUsageModeForExpression(usage); + return usageMode === ts.ModuleKind.ESNext && ts.endsWith(usage.text, ".json" /* Json */); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { var usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== undefined) { @@ -48810,8 +48944,9 @@ var ts; exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); + var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier); - if (!exportDefaultSymbol && !hasSyntheticDefault) { + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); @@ -48825,7 +48960,7 @@ var ts; reportNonDefaultExport(moduleSymbol, node); } } - else if (hasSyntheticDefault) { + else if (hasSyntheticDefault || hasDefaultOnly) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); @@ -48950,7 +49085,7 @@ var ts; var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); - if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } @@ -49309,7 +49444,7 @@ var ts; if (name.kind === 79 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true, false)); if (!symbol) { return getMergedSymbol(symbolFromJSPrototype); } @@ -49344,21 +49479,28 @@ var ts; var namespaceName = getFullyQualifiedName(namespace); var declarationName = ts.declarationNameToString(right); var suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); - var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); - var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); - var canSuggestTypeof = containingQualifiedName && !ts.isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (suggestionForNonexistentModule) { error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + return undefined; } - else if (canSuggestTypeof) { + var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); + var canSuggestTypeof = globalObjectType // <-- can't pull on types if global types aren't initialized yet + && (meaning & 788968 /* Type */) + && containingQualifiedName + && !ts.isTypeOfExpression(containingQualifiedName.parent) + && tryGetQualifiedNameAsValue(containingQualifiedName); + if (canSuggestTypeof) { error(containingQualifiedName, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.entityNameToString(containingQualifiedName)); + return undefined; } - else if (meaning & 1920 /* Namespace */ && exportedTypeSymbol && ts.isQualifiedName(name.parent)) { - error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); - } - else { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + if (meaning & 1920 /* Namespace */ && ts.isQualifiedName(name.parent)) { + var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); + if (exportedTypeSymbol) { + error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); + return undefined; + } } + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); } return undefined; } @@ -49460,7 +49602,7 @@ var ts; : undefined; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - var _a, _b, _c, _d, _e, _f; + var _a, _b, _c, _d, _e, _f, _g; if (isForAugmentation === void 0) { isForAugmentation = false; } if (ts.startsWith(moduleReference, "@types/")) { var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -49480,7 +49622,8 @@ var ts; ((_d = ts.findAncestor(location, ts.isExportDeclaration)) === null || _d === void 0 ? void 0 : _d.moduleSpecifier) || ((_e = (ts.isModuleDeclaration(location) ? location : location.parent && ts.isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)) === null || _e === void 0 ? void 0 : _e.name) || ((_f = (ts.isLiteralImportTypeNode(location) ? location : undefined)) === null || _f === void 0 ? void 0 : _f.argument.literal); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : undefined); // TODO: GH#18217 + var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -49493,6 +49636,9 @@ var ts; if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) { error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); } + if (mode === ts.ModuleKind.ESNext && compilerOptions.resolveJsonModule && resolvedModule.extension === ".json" /* Json */) { + error(errorNode, ts.Diagnostics.JSON_imports_are_experimental_in_ES_module_mode_imports); + } } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); @@ -49543,6 +49689,10 @@ var ts; } else { var tsExtension = ts.tryExtractTSExtension(moduleReference); + var isExtensionlessRelativePathImport = ts.pathIsRelative(moduleReference) && !ts.hasExtension(moduleReference); + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var resolutionIsNode12OrNext = moduleResolutionKind === ts.ModuleResolutionKind.Node12 || + moduleResolutionKind === ts.ModuleResolutionKind.NodeNext; if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension); @@ -49562,6 +49712,19 @@ var ts; ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } + else if (mode === ts.ModuleKind.ESNext && resolutionIsNode12OrNext && isExtensionlessRelativePathImport) { + var absoluteRef_1 = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(currentSourceFile.path)); + var suggestedExt = (_g = suggestedExtensions.find(function (_a) { + var actualExt = _a[0], _importExt = _a[1]; + return host.fileExists(absoluteRef_1 + actualExt); + })) === null || _g === void 0 ? void 0 : _g[1]; + if (suggestedExt) { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + } + else { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -49631,40 +49794,50 @@ var ts; error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } - if (ts.getESModuleInterop(compilerOptions)) { - var referenceParent = referencingLocation.parent; - if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || - ts.isImportCall(referenceParent)) { - var type = getTypeOfSymbol(symbol); + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var reference = ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier; + var type = getTypeOfSymbol(symbol); + var defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); + if (defaultOnlyType) { + return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); + } + if (ts.getESModuleInterop(compilerOptions)) { 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, ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier); - // 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 = new ts.Map(symbol.members); - if (symbol.exports) - result.exports = new ts.Map(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.indexInfos); - return result; + if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); + return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } } } } return symbol; } + /** + * Create a new symbol which has the module's type less the call and construct signatures + */ + function cloneTypeAsModuleType(symbol, moduleType, referenceParent) { + 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 = new ts.Map(symbol.members); + if (symbol.exports) + result.exports = new ts.Map(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.indexInfos); + return result; + } function hasExportAssignmentSymbol(moduleSymbol) { return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } @@ -49693,8 +49866,8 @@ var ts; if (exportEquals !== moduleSymbol) { var type = getTypeOfSymbol(exportEquals); if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { - getPropertiesOfType(type).forEach(function (symbol) { - cb(symbol, symbol.escapedName); + forEachPropertyOfType(type, function (symbol, escapedName) { + cb(symbol, escapedName); }); } } @@ -50026,12 +50199,15 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + if (isNamedMember(symbol, id)) { (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } + function isNamedMember(member, escapedName) { + return !isReservedMemberName(escapedName) && symbolIsValue(member); + } function getNamedOrIndexSignatureMembers(members) { var result = getNamedMembers(members); var index = getIndexSymbolFromSymbolTable(members); @@ -50906,7 +51082,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined; var templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), context); - var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode); + var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } @@ -56864,6 +57040,16 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function forEachPropertyOfType(type, action) { + type = getReducedApparentType(type); + if (type.flags & 3670016 /* StructuredType */) { + resolveStructuredTypeMembers(type).members.forEach(function (symbol, escapedName) { + if (isNamedMember(symbol, escapedName)) { + action(symbol, escapedName); + } + }); + } + } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { var list = obj.properties; return list.some(function (property) { @@ -57800,7 +57986,7 @@ var ts; return false; switch (node.kind) { case 79 /* Identifier */: - return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; case 166 /* PropertyDeclaration */: case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: @@ -59149,6 +59335,8 @@ var ts; // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { includes |= flags & 205258751 /* IncludesMask */; + if (flags & 465829888 /* Instantiable */) + includes |= 33554432 /* IncludesInstantiable */; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { @@ -59257,7 +59445,7 @@ var ts; var _loop_16 = function () { i--; var t = types[i]; - if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) { + if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { ts.orderedRemoveItemAt(types, i); } }; @@ -59362,7 +59550,7 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + var objectFlags = (includes & 36323363 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | (includes & 2097152 /* Intersection */ ? 33554432 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } @@ -60339,12 +60527,6 @@ var ts; } return type[cache] = type; } - function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { - var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); - var checkType = type.checkType; - var extendsType = type.extendsType; - return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); - } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -60653,6 +60835,10 @@ var ts; } return result; } + function isDistributionDependent(root) { + return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || + isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType)); + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -61452,7 +61638,9 @@ var ts; return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { if (!type.declaration.nameType) { - if (isArrayType(t)) { + var constraint = void 0; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && + (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, ts.or(isArrayType, isTupleType))) { return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); } if (isGenericTupleType(t)) { @@ -62992,13 +63180,12 @@ var ts; traceUnionsOrIntersectionsTooLarge(source, target); var result = 0 /* False */; var saveErrorInfo = captureErrorCalculationState(); - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { - result = getConstituentCount(source) * getConstituentCount(target) >= 4 ? - recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags) : - structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) { + // We skip caching when source or target is a union with no more than three constituents. + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + } + else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { + result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags); } if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { @@ -63455,19 +63642,19 @@ var ts; var maybeStart = maybeCount; maybeKeys[maybeCount] = id; maybeCount++; + var saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { sourceStack[sourceDepth] = source; sourceDepth++; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) + expandingFlags |= 1 /* Source */; } if (recursionFlags & 2 /* Target */) { targetStack[targetDepth] = target; targetDepth++; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) + expandingFlags |= 2 /* Target */; } - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) - expandingFlags |= 1 /* Source */; - if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) - expandingFlags |= 2 /* Target */; var originalHandler; var propagatingVarianceFlags = 0; if (outofbandVarianceMarkerHandler) { @@ -63491,13 +63678,13 @@ var ts; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } - expandingFlags = saveExpandingFlags; if (recursionFlags & 1 /* Source */) { sourceDepth--; } if (recursionFlags & 2 /* Target */) { targetDepth--; } + expandingFlags = saveExpandingFlags; if (result) { if (result === -1 /* True */ || (sourceDepth === 0 && targetDepth === 0)) { if (result === -1 /* True */ || result === 3 /* Maybe */) { @@ -63738,7 +63925,7 @@ var ts; originalErrorInfo = undefined; } } - else if (isGenericMappedType(target)) { + else if (isGenericMappedType(target) && relation !== identityRelation) { // Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`. var keysRemapped = !!target.declaration.nameType; var templateType = getTemplateTypeFromMappedType(target); @@ -63802,32 +63989,28 @@ var ts; } } else if (target.flags & 16777216 /* Conditional */) { - var c = target; - // Check if the conditional is always true or always false but still deferred for distribution purposes - var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); - var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); - // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, - // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when - // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, - // to which `{x: string | number, y: string | number}` isn't assignable) - var distributionMapper = void 0; - var checkVar = getActualTypeVariable(c.root.checkType); - if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { - var newParam = cloneTypeParameter(checkVar); - distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); - newParam.mapper = distributionMapper; - } - // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) - var expanding = isDeeplyNestedType(target, targetStack, targetDepth); - var localResult = expanding ? 3 /* Maybe */ : undefined; - if (skipTrue || expanding || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false))) { - if (!skipFalse && !expanding) { - localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); - } - } - if (localResult) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { resetErrorInfo(saveErrorInfo); - return localResult; + return 3 /* Maybe */; + } + var c = target; + // We check for a relationship to a conditional type target only when the conditional type has no + // 'infer' positions and is not distributive or is distributive but doesn't reference the check type + // parameter in either of the result types. + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) { + // Check if the conditional is always true or always false but still deferred for distribution purposes. + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + if (result = skipTrue ? -1 /* True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false)) { + result &= skipFalse ? -1 /* True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + } } } else if (target.flags & 134217728 /* TemplateLiteral */) { @@ -63839,8 +64022,7 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_9 = inferTypesFromTemplateLiteralType(source, target); - if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* True */; } } @@ -63898,33 +64080,34 @@ var ts; } } else if (source.flags & 16777216 /* Conditional */) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { + resetErrorInfo(saveErrorInfo); + return 3 /* Maybe */; + } if (target.flags & 16777216 /* Conditional */) { - // If one of the conditionals under comparison seems to be infinitely expanding, stop comparing it - back out, try - // the constraint, and failing that, give up trying to relate the two. This is the only way we can handle recursive conditional - // types, which might expand forever. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth) && !isDeeplyNestedType(target, targetStack, targetDepth)) { - // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if - // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, - // and Y1 is related to Y2. - var sourceParams = source.root.inferTypeParameters; - var sourceExtends = source.extendsType; - var mapper = void 0; - if (sourceParams) { - // If the source has infer type parameters, we instantiate them in the context of the target - var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); - sourceExtends = instantiateType(sourceExtends, ctx.mapper); - mapper = ctx.mapper; - } - if (isTypeIdenticalTo(sourceExtends, target.extendsType) && - (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { - if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + var sourceParams = source.root.inferTypeParameters; + var sourceExtends = source.extendsType; + var mapper = void 0; + if (sourceParams) { + // If the source has infer type parameters, we instantiate them in the context of the target + var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); + sourceExtends = instantiateType(sourceExtends, ctx.mapper); + mapper = ctx.mapper; + } + if (isTypeIdenticalTo(sourceExtends, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { + if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -63939,17 +64122,13 @@ var ts; } } } - // We'll repeatedly decompose source side conditionals if they're recursive - check if we've already recured on the constraint a lot and, if so, bail - // on the comparison. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth)) { - // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` - // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). - var defaultConstraint = getDefaultConstraintOfConditionalType(source); - if (defaultConstraint) { - if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` + // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64038,9 +64217,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_10) { - return result_10; + var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_9) { + return result_9; } } } @@ -64112,13 +64291,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_11; + var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { + if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); + return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); } } } @@ -65058,14 +65237,15 @@ var ts; // `type A = null extends T ? [A>] : [T]` // has expanded into `[A>>>>>]` // in such cases we need to terminate the expansion, and we do so here. - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5) { + function isDeeplyNestedType(type, stack, depth, maxDepth) { + if (maxDepth === void 0) { maxDepth = 5; } + if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; for (var i = 0; i < depth; i++) { if (getRecursionIdentity(stack[i]) === identity_1) { count++; - if (count >= 5) { + if (count >= maxDepth) { return true; } } @@ -65806,7 +65986,8 @@ var ts; (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { var newName = "arg" + param.parent.parameters.indexOf(param); - errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + var typeName = ts.declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); return; } diagnostic = declaration.dotDotDotToken ? @@ -66200,6 +66381,10 @@ var ts; inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : undefined; } + function isTypeMatchedByTemplateLiteralType(source, target) { + var inferences = inferTypesFromTemplateLiteralType(source, target); + return !!inferences && ts.every(inferences, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); }); + } function getStringLikeTypeForType(type) { return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); } @@ -66976,17 +67161,16 @@ var ts; var inferredType = void 0; var signature = context.signature; if (signature) { - var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + var inferredCovariantType_1 = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - var inferredContravariantType = getContravariantInference(inference); // If we have both co- and contra-variant inferences, we prefer the contra-variant inference - // unless the co-variant inference is a subtype and not 'never'. - inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && - isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? - inferredCovariantType : inferredContravariantType; + // unless the co-variant inference is a subtype of some contra-variant inference and not 'never'. + inferredType = inferredCovariantType_1 && !(inferredCovariantType_1.flags & 131072 /* Never */) && + ts.some(inference.contraCandidates, function (t) { return isTypeSubtypeOf(inferredCovariantType_1, t); }) ? + inferredCovariantType_1 : getContravariantInference(inference); } - else if (inferredCovariantType) { - inferredType = inferredCovariantType; + else if (inferredCovariantType_1) { + inferredType = inferredCovariantType_1; } else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -67087,8 +67271,7 @@ var ts; if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), - /*excludeGlobals*/ false, - /*issueSuggestions*/ true) || unknownSymbol; + /*excludeGlobals*/ false) || unknownSymbol; } return links.resolvedSymbol; } @@ -67105,8 +67288,11 @@ var ts; function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 79 /* Identifier */: - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + if (!ts.isThisInTypeQuery(node)) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + } + // falls through case 108 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); case 229 /* NonNullExpression */: @@ -67286,8 +67472,9 @@ var ts; // constituent types keyed by the literal types of the property by that name in each constituent type. function getKeyPropertyName(unionType) { var types = unionType.types; - // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + // We only construct maps for unions with many non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */ || + ts.countWhere(types, function (t) { return !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */)); }) < 10) { return undefined; } if (unionType.keyPropertyName === undefined) { @@ -67320,7 +67507,7 @@ var ts; var keyPropertyName = getKeyPropertyName(unionType); var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 294 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); - var propType = propNode && getTypeOfExpression(propNode.initializer); + var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } function isOrContainsMatchingReference(source, target) { @@ -67736,7 +67923,7 @@ var ts; mapType(type, mapper); } function getConstituentCount(type) { - return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; + return type.flags & 1048576 /* Union */ ? type.types.length : 1; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -69234,7 +69421,7 @@ var ts; return parent.kind === 205 /* PropertyAccessExpression */ || parent.kind === 207 /* CallExpression */ && parent.expression === node || parent.kind === 206 /* ElementAccessExpression */ && parent.expression === node && - !(isGenericTypeWithoutNullableConstraint(type) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); + !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); @@ -70555,7 +70742,7 @@ var ts; return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 294 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -71110,6 +71297,10 @@ var ts; function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { + if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) { + return links.resolvedType = errorType; + } links.resolvedType = checkExpression(node.expression); // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. // (It needs to be bound at class evaluation time.) @@ -72579,7 +72770,7 @@ var ts; if (relatedInfo) { ts.addRelatedInfo(resultDiagnostic, relatedInfo); } - addErrorOrSuggestion(!isUncheckedJS, resultDiagnostic); + addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && @@ -72652,7 +72843,19 @@ var ts; // 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 // So the table *contains* `x` but `x` isn't actually in scope. // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. - return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + if (symbol) + return symbol; + var candidates; + if (symbols === globals) { + var primitives = ts.mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], function (s) { return symbols.has((s.charAt(0).toUpperCase() + s.slice(1))) + ? createSymbol(524288 /* TypeAlias */, s) + : undefined; }); + candidates = primitives.concat(ts.arrayFrom(symbols.values())); + } + else { + candidates = ts.arrayFrom(symbols.values()); + } + return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), candidates, meaning); }); return result; } @@ -74818,11 +75021,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } } return createPromiseReturnType(node, anyType); } + function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.parent = originalSymbol; + newSymbol.nameType = getStringLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + return createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + } + function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { + var hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier); + if (hasDefaultOnly && type && !isErrorType(type)) { + var synthType = type; + if (!synthType.defaultOnlyType) { + var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_4; + } + return synthType.defaultOnlyType; + } + return undefined; + } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { var _a; if (allowSyntheticDefaultImports && type && !isErrorType(type)) { @@ -74831,14 +75056,8 @@ var ts; var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false, moduleSpecifier); if (hasSyntheticDefault) { - var memberTable = ts.createSymbolTable(); - var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); - newSymbol.parent = originalSymbol; - newSymbol.nameType = getStringLiteralType("default"); - newSymbol.target = resolveSymbol(symbol); - memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); - var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); anonymousSymbol.type = defaultContainingObject; synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; } @@ -75546,12 +75765,12 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; + var type_5 = getBaseConstraintOfType(operandType) || operandType; // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_4.flags & 3 /* AnyOrUnknown */) { + if (type_5.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */; } - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -78141,7 +78360,9 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + if (!typeParameters) + return undefined; var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -78152,7 +78373,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); + checkIndexConstraints(type, type.symbol); checkTypeForDuplicateIndexSignatures(node); checkObjectTypeForDuplicateDeclarations(node); } @@ -78247,6 +78468,7 @@ var ts; checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { + checkGrammarMappedType(node); checkSourceElement(node.typeParameter); checkSourceElement(node.nameType); checkSourceElement(node.type); @@ -78263,6 +78485,12 @@ var ts; checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); } } + function checkGrammarMappedType(node) { + var _a; + if ((_a = node.members) === null || _a === void 0 ? void 0 : _a.length) { + return grammarErrorOnNode(node.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + } function checkThisType(node) { getTypeFromThisTypeNode(node); } @@ -78640,12 +78868,12 @@ var ts; case 264 /* ImportEqualsDeclaration */: case 267 /* NamespaceImport */: case 266 /* ImportClause */: - var result_12 = 0 /* None */; + var result_11 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { - result_12 |= getDeclarationSpaces(d); + result_11 |= getDeclarationSpaces(d); }); - return result_12; + return result_11; case 253 /* VariableDeclaration */: case 202 /* BindingElement */: case 255 /* FunctionDeclaration */: @@ -81208,7 +81436,7 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type, isStaticIndex) { + function checkIndexConstraints(type, symbol, isStaticIndex) { var indexInfos = getIndexInfosOfType(type); if (indexInfos.length === 0) { return; @@ -81219,15 +81447,15 @@ var ts; checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */, /*includeNonPublic*/ true), getNonMissingTypeOfSymbol(prop)); } } - var typeDeclaration = type.symbol.valueDeclaration; + var typeDeclaration = symbol.valueDeclaration; if (typeDeclaration && ts.isClassLike(typeDeclaration)) { for (var _b = 0, _c = typeDeclaration.members; _b < _c.length; _b++) { var member = _c[_b]; // Only process instance properties with computed names here. Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. if (!ts.isStatic(member) && !hasBindableName(member)) { - var symbol = getSymbolOfNode(member); - checkIndexConstraintForProperty(type, symbol, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol)); + var symbol_3 = getSymbolOfNode(member); + checkIndexConstraintForProperty(type, symbol_3, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol_3)); } } } @@ -81514,7 +81742,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); + checkMembersForOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -81543,14 +81771,13 @@ var ts; } } if (produceDiagnostics) { - checkIndexConstraints(type); - checkIndexConstraints(staticType, /*isStaticIndex*/ true); + checkIndexConstraints(type, symbol); + checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { - var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) { var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; @@ -81562,46 +81789,71 @@ var ts; if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { - checkClassMember(param, /*memberIsParameterProperty*/ true); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, + /* memberIsParameterProperty */ true); } }); } - checkClassMember(member); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, + /* memberIsParameterProperty */ false); }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; _loop_29(member); } - function checkClassMember(member, memberIsParameterProperty) { - var hasOverride = ts.hasOverrideModifier(member); - var hasStatic = ts.isStatic(member); - var isJs = ts.isInJSFile(member); - if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { - var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); - if (!declaredProp) { - return; - } - var thisType = hasStatic ? staticType : typeWithThis; - var baseType = hasStatic ? baseStaticType : baseWithThis; - var prop = getPropertyOfType(thisType, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); - var baseClassName = typeToString(baseWithThis); - if (prop && !baseProp && hasOverride) { - var suggestion = getSuggestedSymbolForNonexistentClassMember(ts.symbolName(declaredProp), baseType); + } + /** + * @param member Existing member node to be checked. + * Note: `member` cannot be a synthetic node. + */ + function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { + if (reportErrors === void 0) { reportErrors = true; } + var declaredProp = member.name + && getSymbolAtLocation(member.name) + || getSymbolAtLocation(member); + if (!declaredProp) { + return 0 /* Ok */; + } + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, ts.hasOverrideModifier(member), ts.hasAbstractModifier(member), ts.isStatic(member), memberIsParameterProperty, ts.symbolName(declaredProp), reportErrors ? member : undefined); + } + /** + * Checks a class member declaration for either a missing or an invalid `override` modifier. + * Note: this function can be used for speculative checking, + * i.e. checking a member that does not yet exist in the program. + * An example of that would be to call this function in a completions scenario, + * when offering a method declaration as completion. + * @param errorNode The node where we should report an error, or undefined if we should not report errors. + */ + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { + var isJs = ts.isInJSFile(node); + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { + var memberEscapedName = ts.escapeLeadingUnderscores(memberName); + var thisType = memberIsStatic ? staticType : typeWithThis; + var baseType = memberIsStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, memberEscapedName); + var baseProp = getPropertyOfType(baseType, memberEscapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && memberHasOverrideModifier) { + if (errorNode) { + var suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); // Again, using symbol name: note that's different from `symbol.escapedName` suggestion ? - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } - else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { - var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); - if (hasOverride) { - return; - } - if (!baseHasAbstract) { + return 2 /* HasInvalidOverride */; + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); + if (memberHasOverrideModifier) { + return 0 /* Ok */; + } + if (!baseHasAbstract) { + if (errorNode) { var diag = memberIsParameterProperty ? isJs ? ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : @@ -81609,20 +81861,28 @@ var ts; isJs ? ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; - error(member, diag, baseClassName); + error(errorNode, diag, baseClassName); } - else if (ts.hasAbstractModifier(member) && baseHasAbstract) { - error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + return 1 /* NeedsOverride */; + } + else if (memberHasAbstractModifier && baseHasAbstract) { + if (errorNode) { + error(errorNode, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); } + return 1 /* NeedsOverride */; } } - else if (hasOverride) { + } + else if (memberHasOverrideModifier) { + if (errorNode) { var className = typeToString(type); - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } + return 2 /* HasInvalidOverride */; } + return 0 /* Ok */; } 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 @@ -81665,6 +81925,31 @@ var ts; } } } + /** + * Checks a member declaration node to see if has a missing or invalid `override` modifier. + * @param node Class-like node where the member is declared. + * @param member Member declaration node. + * Note: `member` can be a synthetic node without a parent. + */ + function getMemberOverrideModifierStatus(node, member) { + if (!member.name) { + return 0 /* Ok */; + } + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var memberHasOverrideModifier = member.parent + ? ts.hasOverrideModifier(member) + : ts.hasSyntacticModifier(member, 16384 /* Override */); + var memberName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name)); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, ts.hasAbstractModifier(member), ts.isStatic(member), + /* memberIsParameterProperty */ false, memberName); + } function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -81935,7 +82220,7 @@ var ts; var baseType = _a[_i]; checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); } - checkIndexConstraints(type); + checkIndexConstraints(type, symbol); } } checkObjectTypeForDuplicateDeclarations(node); @@ -86126,6 +86411,9 @@ var ts; } } function checkGrammarProperty(node) { + if (ts.isComputedPropertyName(node.name) && ts.isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101 /* InKeyword */) { + return grammarErrorOnNode(node.parent.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } if (ts.isClassLike(node.parent)) { if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); @@ -86145,7 +86433,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 181 /* TypeLiteral */) { + else if (ts.isTypeLiteralNode(node.parent)) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -86822,7 +87110,7 @@ var ts; return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); case 194 /* MappedType */: ts.Debug.type(node); - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 195 /* LiteralType */: ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); @@ -94658,11 +94946,11 @@ var ts; currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } - function getJsxFactoryCalleePrimitive(childrenLength) { - return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx"; + function getJsxFactoryCalleePrimitive(isStaticChildren) { + return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx"; } - function getJsxFactoryCallee(childrenLength) { - var type = getJsxFactoryCalleePrimitive(childrenLength); + function getJsxFactoryCallee(isStaticChildren) { + var type = getJsxFactoryCalleePrimitive(isStaticChildren); return getImplicitImportForName(type); } function getImplicitJsxFragmentReference() { @@ -94809,60 +95097,37 @@ var ts; return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node); } function convertJsxChildrenToChildrenPropObject(children) { + var prop = convertJsxChildrenToChildrenPropAssignment(children); + return prop && factory.createObjectLiteralExpression([prop]); + } + function convertJsxChildrenToChildrenPropAssignment(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); - if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) - ]); + if (ts.length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) { + var result_12 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_12 && factory.createPropertyAssignment("children", result_12); } var result = ts.mapDefined(children, transformJsxChildToExpression); - return !result.length ? undefined : factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) - ]); + return ts.length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined; } function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; + var childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined; var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; }); var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties; - var segments = []; - if (attrs.length) { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - } - if (children && children.length) { - var result = convertJsxChildrenToChildrenPropObject(children); - if (result) { - segments.push(result); - } - } - if (segments.length === 0) { - objectProperties = factory.createObjectLiteralExpression([]); - // When there are no attributes, React wants {} - } - else { - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments); - } - return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location); + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : + factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : ts.emptyArray); // When there are no attributes, React wants {} + return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || ts.emptyArray, isChild, location); } - function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) { + function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { + var _a; + var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); + var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; if (compilerOptions.jsx === 5 /* ReactJSXDev */) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { // isStaticChildren development flag - args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse()); + args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); // __source development flag var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos); args.push(factory.createObjectLiteralExpression([ @@ -94874,7 +95139,7 @@ var ts; args.push(factory.createThis()); } } - var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location); + var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args), location); if (isChild) { ts.startOnNewLine(element); } @@ -94882,38 +95147,9 @@ var ts; } function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; var attrs = node.attributes.properties; - if (attrs.length === 0) { - objectProperties = factory.createNull(); - // When there are no attributes, React wants "null" - } - else { - var target = ts.getEmitScriptTarget(compilerOptions); - if (target && target >= 5 /* ES2018 */) { - objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { - return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); - }))); - } - else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); - } - } - } + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs) : + factory.createNull(); // When there are no attributes, React wants "null" var callee = currentFileState.importSpecifier === undefined ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 node) @@ -94933,7 +95169,7 @@ var ts; } } return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), - /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location); + /*keyAttr*/ undefined, children, isChild, location); } function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 @@ -94946,6 +95182,36 @@ var ts; function transformJsxSpreadAttributeToSpreadAssignment(node) { return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); } + function transformJsxAttributesToObjectProps(attrs, children) { + var target = ts.getEmitScriptTarget(compilerOptions); + return target && target >= 5 /* ES2018 */ ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : + transformJsxAttributesToExpression(attrs, children); + } + function transformJsxAttributesToProps(attrs, children) { + var props = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return ts.map(attrs, function (attr) { return isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr); }); + })); + if (children) { + props.push(children); + } + return props; + } + function transformJsxAttributesToExpression(attrs, children) { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var expressions = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + expressions.unshift(factory.createObjectLiteralExpression()); + } + if (children) { + expressions.push(factory.createObjectLiteralExpression([children])); + } + return ts.singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -98361,78 +98627,17 @@ var ts; * @param node A TemplateExpression node. */ function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - // createAdd will check if each expression binds less closely than binary '+'. - // If it does, it wraps the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var expression = ts.reduceLeft(expressions, factory.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - /** - * Gets a value indicating whether we need to include the head of a TemplateExpression. - * - * @param node A TemplateExpression node. - */ - function shouldAddTemplateHead(node) { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - /** - * Adds the head of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(factory.createStringLiteral(node.head.text)); - } - /** - * Visits and adds the template spans of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateSpans(expressions, node) { + var expression = factory.createStringLiteral(node.head.text); for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { var span = _a[_i]; - expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span.literal.text.length !== 0) { - expressions.push(factory.createStringLiteral(span.literal.text)); + var args = [ts.visitNode(span.expression, visitor, ts.isExpression)]; + if (span.literal.text.length > 0) { + args.push(factory.createStringLiteral(span.literal.text)); } + expression = factory.createCallExpression(factory.createPropertyAccessExpression(expression, "concat"), + /*typeArguments*/ undefined, args); } + return ts.setTextRange(expression, node); } /** * Visits the `super` keyword @@ -108052,7 +108257,14 @@ var ts; // clear the parenthesizer rule as we ascend currentParenthesizerRule = undefined; } - function pipelineEmitWithHintWorker(hint, node) { + function pipelineEmitWithHintWorker(hint, node, allowSnippets) { + if (allowSnippets === void 0) { allowSnippets = true; } + if (allowSnippets) { + var snippet = ts.getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -108661,6 +108873,28 @@ var ts; } } // + // Snippet Elements + // + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1 /* Placeholder */: + emitPlaceholder(hint, node, snippet); + break; + case 0 /* TabStop */: + emitTabStop(snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite("${" + snippet.order + ":"); // `${2:` + pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...` + nonEscapingWrite("}"); // `}` + // `${2:...}` + } + function emitTabStop(snippet) { + nonEscapingWrite("$" + snippet.order); + } + // // Identifiers // function emitIdentifier(node) { @@ -110899,6 +111133,15 @@ var ts; function writeProperty(s) { writer.writeProperty(s); } + function nonEscapingWrite(s) { + // This should be defined in a snippet-escaping text writer. + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } + else { + writer.write(s); + } + } function writeLine(count) { if (count === void 0) { count = 1; } for (var i = 0; i < count; i++) { @@ -112168,7 +112411,7 @@ var ts; var rootResult = tryReadDirectory(rootDir, rootDirPath); var rootSymLinkResult; if (rootResult !== undefined) { - return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -113140,7 +113383,7 @@ var ts; break; case ts.FileIncludeKind.TypeReferenceDirective: (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end); - packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), getModeForResolutionAtIndex(file, index))) === null || _g === void 0 ? void 0 : _g.packageId; + packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId; break; case ts.FileIncludeKind.LibReferenceDirective: (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end); @@ -113702,15 +113945,15 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_13 = []; var i = 0; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i)); i++; - result_14.push(resolvedModule); + result_13.push(resolvedModule); } - return result_14; + return result_13; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -114002,8 +114245,8 @@ var ts; var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); }); var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile); // ensure that types resolutions are still correct - var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); - if (typeReferenceEesolutionsChanged) { + var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); + if (typeReferenceResolutionsChanged) { structureIsReused = 1 /* SafeModules */; newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions); } @@ -115291,6 +115534,21 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { + var isNightly = ts.stringContains(ts.version, "-dev"); + if (!isNightly) { + if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); + } + else if (ts.getEmitModuleKind(options) === ts.ModuleKind.NodeNext) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext"); + } + } if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } @@ -115439,7 +115697,9 @@ var ts; } } if (options.resolveJsonModule) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } // Any emit other than common js, amd, es2015 or esnext is error @@ -115767,8 +116027,8 @@ var ts; function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + function createOptionValueDiagnostic(option1, message, arg0, arg1) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1); } function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); @@ -118012,6 +118272,9 @@ var ts; else { resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile); perDirectoryResolution.set(name, mode, resolution); + if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { + resolutionHost.onDiscoveredSymlink(); + } } resolutionsInFile.set(name, mode, resolution); watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); @@ -118480,6 +118743,11 @@ var ts; } } ts.createResolutionCache = createResolutionCache; + function resolutionIsSymlink(resolution) { + var _a, _b; + return !!(((_a = resolution.resolvedModule) === null || _a === void 0 ? void 0 : _a.originalPath) || + ((_b = resolution.resolvedTypeReferenceDirective) === null || _b === void 0 ? void 0 : _b.originalPath)); + } })(ts || (ts = {})); // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ @@ -118772,9 +119040,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_14 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_14) + return result_14; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -118794,10 +119062,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_15 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_15) + return result_15; } }); }); @@ -119090,13 +119358,15 @@ var ts; if (host.fileExists(packageJsonPath)) { var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); // TODO: Inject `require` or `import` condition based on the intended import mode - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; - if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; - return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); - } - if (packageJsonContent.exports) { - return { moduleFileToTry: path, blockedByExports: true }; + if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + if (fromExports) { + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); + } + if (packageJsonContent.exports) { + return { moduleFileToTry: path, blockedByExports: true }; + } } var versionPaths = packageJsonContent.typesVersions ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -120138,6 +120408,9 @@ var ts; sourceFilesCache.set(path, false); } } + if (sourceFile) { + sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); + } return sourceFile; } return hostSourceFile.sourceFile; @@ -121094,11 +121367,11 @@ var ts; (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [state.host.realpath ? toPath(state, state.host.realpath(path)) : path, data]; - })); if (state.watch) { + state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { + var path = _a[0], data = _a[1]; + return [state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data]; + })); state.builderPrograms.set(projectPath, program); } step++; @@ -123490,28 +123763,85 @@ var ts; /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { var current = sourceFile; - outer: while (true) { + var foundToken; + var _loop_1 = function () { // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { - var child = _a[_i]; - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + var children = current.getChildren(sourceFile); + var i = ts.binarySearchKey(children, position, function (_, i) { return i; }, function (middle, _) { + // This last callback is more of a selector than a comparator - + // `EqualTo` causes the `middle` result to be returned + // `GreaterThan` causes recursion on the left of the middle + // `LessThan` causes recursion on the right of the middle + // Let's say you have 3 nodes, spanning positons + // pos: 1, end: 3 + // pos: 3, end: 3 + // pos: 3, end: 5 + // and you're looking for the token at positon 3 - all 3 of these nodes are overlapping with position 3. + // In fact, there's a _good argument_ that node 2 shouldn't even be allowed to exist - depending on if + // the start or end of the ranges are considered inclusive, it's either wholly subsumed by the first or the last node. + // Unfortunately, such nodes do exist. :( - See fourslash/completionsImport_tsx.tsx - empty jsx attributes create + // a zero-length node. + // What also you may not expect is that which node we return depends on the includePrecedingTokenAtEndPosition flag. + // Specifically, if includePrecedingTokenAtEndPosition is set, we return the 1-3 node, while if it's unset, we + // return the 3-5 node. (The zero length node is never correct.) This is because the includePrecedingTokenAtEndPosition + // flag causes us to return the first node whose end position matches the position and which produces and acceptable token + // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the + // position and whose end is greater than the position. + var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { - // If this child begins after position, then all subsequent children will as well. - break; - } - var end = child.getEnd(); - if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { - current = child; - continue outer; + return 1 /* GreaterThan */; } - else if (includePrecedingTokenAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { - return previousToken; + // first element whose start position is before the input and whose end position is after or equal to the input + if (nodeContainsPosition(children[middle])) { + if (children[middle - 1]) { + // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position + if (nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } } + return 0 /* EqualTo */; } + // this complex condition makes us left-recur around a zero-length node when includePrecedingTokenAtEndPosition is set, rather than right-recur on it + if (includePrecedingTokenAtEndPosition && start === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } + return -1 /* LessThan */; + }); + if (foundToken) { + return { value: foundToken }; } - return current; + if (i >= 0 && children[i]) { + current = children[i]; + return "continue-outer"; + } + return { value: current }; + }; + outer: while (true) { + var state_1 = _loop_1(); + if (typeof state_1 === "object") + return state_1.value; + switch (state_1) { + case "continue-outer": continue outer; + } + } + function nodeContainsPosition(node) { + var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + return false; + } + var end = node.getEnd(); + if (position < end || (position === end && (node.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + return true; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, node); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + foundToken = previousToken; + return true; + } + } + return false; } } /** @@ -124154,14 +124484,14 @@ var ts; return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); } ts.programContainsModules = programContainsModules; - function programContainsEs6Modules(program) { + function programContainsEsModules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } - ts.programContainsEs6Modules = programContainsEs6Modules; - function compilerOptionsIndicateEs6Modules(compilerOptions) { + ts.programContainsEsModules = programContainsEsModules; + function compilerOptionsIndicateEsModules(compilerOptions) { return !!compilerOptions.module || ts.getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ || !!compilerOptions.noEmit; } - ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + ts.compilerOptionsIndicateEsModules = compilerOptionsIndicateEsModules; function createModuleSpecifierResolutionHost(program, host) { // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. @@ -124548,9 +124878,9 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.linkText); } ts.linkTextPart = linkTextPart; - function linkNamePart(name, target) { + function linkNamePart(text, target) { return { - text: ts.getTextOfNode(name), + text: text, kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], target: { fileName: ts.getSourceFileOfNode(target).fileName, @@ -124575,20 +124905,41 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var suffix = findLinkNameEnd(link.text); + var name = ts.getTextOfNode(link.name) + link.text.slice(0, suffix); + var text = link.text.slice(suffix); var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); if (decl) { - parts.push(linkNamePart(link.name, decl)); - if (link.text) - parts.push(linkTextPart(link.text)); + parts.push(linkNamePart(name, decl)); + if (text) + parts.push(linkTextPart(text)); } else { - parts.push(linkTextPart(ts.getTextOfNode(link.name) + " " + link.text)); + parts.push(linkTextPart(name + (suffix ? "" : " ") + text)); } } parts.push(linkPart("}")); return parts; } ts.buildLinkParts = buildLinkParts; + function findLinkNameEnd(text) { + if (text.indexOf("()") === 0) + return 2; + if (text[0] !== "<") + return 0; + var brackets = 0; + var i = 0; + while (i < text.length) { + if (text[i] === "<") + brackets++; + if (text[i] === ">") + brackets--; + i++; + if (!brackets) + return i; + } + return 0; + } var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -125453,6 +125804,16 @@ var ts; return decisionFromFile !== null && decisionFromFile !== void 0 ? decisionFromFile : program.usesUriStyleNodeCoreModules; } ts.shouldUseUriStyleNodeCoreModules = shouldUseUriStyleNodeCoreModules; + function getNewLineKind(newLineCharacter) { + return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + } + ts.getNewLineKind = getNewLineKind; + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + ts.diagnosticToString = diagnosticToString; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -125492,19 +125853,24 @@ var ts; } var isDefault = exportKind === 1 /* Default */; var namedSymbol = isDefault && ts.getLocalSymbolForExportDefault(symbol) || symbol; - // A re-export merged with an export from a module augmentation can result in `symbol` - // being an external module symbol; the name it is re-exported by will be `symbolTableKey` - // (which comes from the keys of `moduleSymbol.exports`.) - var importedName = ts.isExternalModuleSymbol(namedSymbol) + // 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`. + // 2. A re-export merged with an export from a module augmentation can result in `symbol` + // being an external module symbol; the name it is re-exported by will be `symbolTableKey` + // (which comes from the keys of `moduleSymbol.exports`.) + // 3. Otherwise, we have a default/namespace import that can be imported by any name, and + // `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to + // get a better name. + var importedName = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) ? ts.unescapeLeadingUnderscores(symbolTableKey) : ts.getNameForExportedSymbol(namedSymbol, scriptTarget); var moduleName = ts.stripQuotes(moduleSymbol.name); var id = exportInfoId++; + var target = ts.skipAlias(symbol, checker); var storedSymbol = symbol.flags & 33554432 /* Transient */ ? undefined : symbol; var storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? undefined : moduleSymbol; if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); - exportInfo.add(key(importedName, symbol, moduleName, checker), { + exportInfo.add(key(importedName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { id: id, symbolTableKey: symbolTableKey, symbolName: importedName, @@ -125512,16 +125878,16 @@ var ts; moduleFile: moduleFile, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: exportKind, - targetFlags: ts.skipAlias(symbol, checker).flags, + targetFlags: target.flags, isFromPackageJson: isFromPackageJson, symbol: storedSymbol, moduleSymbol: storedModuleSymbol, }); }, - get: function (importingFile, importedName, symbol, moduleName, checker) { + get: function (importingFile, key) { if (importingFile !== usableByFileName) return; - var result = exportInfo.get(key(importedName, symbol, moduleName, checker)); + var result = exportInfo.get(key); return result === null || result === void 0 ? void 0 : result.map(rehydrateCachedInfo); }, forEach: function (importingFile, action) { @@ -125529,7 +125895,7 @@ var ts; return; exportInfo.forEach(function (info, key) { var _a = parseKey(key), symbolName = _a.symbolName, ambientModuleName = _a.ambientModuleName; - action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName); + action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName, key); }); }, releaseSymbols: function () { @@ -125594,26 +125960,16 @@ var ts; isFromPackageJson: isFromPackageJson, }; } - function key(importedName, symbol, moduleName, checker) { - var unquoted = ts.stripQuotes(moduleName); - var moduleKey = ts.isExternalModuleNameRelative(unquoted) ? "/" : unquoted; - var target = ts.skipAlias(symbol, checker); - return importedName + "|" + createSymbolKey(target) + "|" + moduleKey; + function key(importedName, symbol, ambientModuleName, checker) { + var moduleKey = ambientModuleName || ""; + return importedName + "|" + ts.getSymbolId(ts.skipAlias(symbol, checker)) + "|" + moduleKey; } function parseKey(key) { var symbolName = key.substring(0, key.indexOf("|")); var moduleKey = key.substring(key.lastIndexOf("|") + 1); - var ambientModuleName = moduleKey === "/" ? undefined : moduleKey; + var ambientModuleName = moduleKey === "" ? undefined : moduleKey; return { symbolName: symbolName, ambientModuleName: ambientModuleName }; } - function createSymbolKey(symbol) { - var key = symbol.name; - while (symbol.parent) { - key += "," + symbol.parent.name; - symbol = symbol.parent; - } - return key; - } function fileIsGlobalOnly(file) { return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; } @@ -125623,7 +125979,7 @@ var ts; } var oldFileStatementIndex = -1; var newFileStatementIndex = -1; - var _loop_1 = function (ambientModuleName) { + var _loop_2 = function (ambientModuleName) { var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); @@ -125633,9 +125989,9 @@ var ts; }; for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { var ambientModuleName = _a[_i]; - var state_1 = _loop_1(ambientModuleName); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_2(ambientModuleName); + if (typeof state_2 === "object") + return state_2.value; } return true; } @@ -125735,7 +126091,7 @@ var ts; cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, scriptTarget, checker); } checker.forEachExportAndPropertyOfModule(moduleSymbol, function (exported, key) { - if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, exported)) { + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, key)) { cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, scriptTarget, checker); } }); @@ -127055,7 +127411,7 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { - function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); return entries && convertPathCompletions(entries); @@ -127063,12 +127419,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -127078,7 +127434,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -127477,7 +127833,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_2 = function (name, kind, extension) { + var _loop_3 = function (name, kind, extension) { // 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 === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -127485,7 +127841,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_2(name, kind, extension); + _loop_3(name, kind, extension); } } } @@ -127520,7 +127876,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_3 = function (moduleName) { + var _loop_4 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -127528,7 +127884,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_3(moduleName); + _loop_4(moduleName); } } if (!foundGlobal) { @@ -127804,6 +128160,8 @@ var ts; (function (CompletionSource) { /** Completions that require `this.` insertion text */ CompletionSource["ThisProperty"] = "ThisProperty/"; + /** Auto-import that comes attached to a class member snippet */ + CompletionSource["ClassMemberSnippet"] = "ClassMemberSnippet/"; })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { @@ -127912,7 +128270,6 @@ var ts; } // If the request is a continuation of an earlier `isIncomplete` response, // we can continue it from the cached previous response. - var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a = host.getIncompleteCompletionsCache) === null || _a === void 0 ? void 0 : _a.call(host) : undefined; if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && ts.isIdentifier(previousToken)) { @@ -127924,7 +128281,7 @@ var ts; else { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.clear(); } - var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, typeChecker, compilerOptions, host, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences); if (stringCompletions) { return stringCompletions; } @@ -127938,7 +128295,7 @@ var ts; } switch (completionData.kind) { case 0 /* Data */: - var response = completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); + var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences); if (response === null || response === void 0 ? void 0 : response.isIncomplete) { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.set(response); } @@ -127958,20 +128315,19 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function completionEntryDataIsResolved(data) { + return !!(data === null || data === void 0 ? void 0 : data.moduleSpecifier); + } function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken) { - var _a; var previousResponse = cache.get(); if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var checker = program.getTypeChecker(); - var autoImportProvider = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); - var autoImportProviderChecker = autoImportProvider === null || autoImportProvider === void 0 ? void 0 : autoImportProvider.getTypeChecker(); var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, preferences, /*isForImportStatementCompletion*/ false, function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { - if (!entry.hasAction || !entry.source || !entry.data || entry.data.moduleSpecifier) { + if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) { // Not an auto import or already resolved; keep as is return entry; } @@ -127979,8 +128335,8 @@ var ts; // No longer matches typed characters; filter out return undefined; } - var _a = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)), symbol = _a.symbol, origin = _a.origin; - var info = exportMap.get(file.path, entry.name, symbol, origin.moduleSymbol.name, origin.isFromPackageJson ? autoImportProviderChecker : checker); + var origin = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)).origin; + var info = exportMap.get(file.path, entry.data.exportMapKey); var result = info && context.tryResolve(info, !ts.isExternalModuleNameRelative(ts.stripQuotes(origin.moduleSymbol.name))); if (!result) return entry; @@ -128036,7 +128392,7 @@ var ts; // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 79 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; // Verify if the file is JSX language variant if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { @@ -128048,7 +128404,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); // TODO: GH#18217 } else { @@ -128056,7 +128412,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -128162,14 +128518,16 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { - var _a; + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind) { + var _a, _b; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(replacementToken); var data; var isSnippet; + var source = getSourceFromOrigin(origin); var sourceDisplay; var hasAction; + var typeChecker = program.getTypeChecker(); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -128220,12 +128578,16 @@ var ts; isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; } } - if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { - return undefined; - } - if (originIsExport(origin) || originIsResolvedExport(origin)) { - data = originToCompletionEntryData(origin); - hasAction = !importCompletionNode; + if (preferences.includeCompletionsWithClassMemberSnippets && + preferences.includeCompletionsWithInsertText && + completionKind === 3 /* MemberLike */ && + isClassLikeMemberCompletion(symbol, location)) { + var importAdder = void 0; + (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); + if (importAdder === null || importAdder === void 0 ? void 0 : importAdder.hasFixes()) { + hasAction = true; + source = CompletionSource.ClassMemberSnippet; + } } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location); if (kind === "JSX attribute" /* jsxAttribute */ && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { @@ -128237,7 +128599,7 @@ var ts; && !(type.flags & 1048576 /* Union */ && ts.find(type.types, function (type) { return !!(type.flags & 528 /* BooleanLike */); }))) { if (type.flags & 402653316 /* StringLike */ || (type.flags & 1048576 /* Union */ && ts.every(type.types, function (type) { return !!(type.flags & (402653316 /* StringLike */ | 32768 /* Undefined */)); }))) { // If is string like or undefined use quotes - insertText = escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); + insertText = ts.escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); isSnippet = true; } else { @@ -128246,12 +128608,16 @@ var ts; } } if (useBraces_1) { - insertText = escapeSnippetText(name) + "={$1}"; + insertText = ts.escapeSnippetText(name) + "={$1}"; isSnippet = true; } - if (isSnippet) { - replacementSpan = ts.createTextSpanFromNode(location, sourceFile); - } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = originToCompletionEntryData(origin); + hasAction = !importCompletionNode; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but @@ -128265,7 +128631,7 @@ var ts; kind: kind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), sortText: sortText, - source: getSourceFromOrigin(origin), + source: source, hasAction: hasAction ? true : undefined, isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, @@ -128277,17 +128643,222 @@ var ts; data: data, }; } - function escapeSnippetText(text) { - return text.replace(/\$/gm, "\\$"); + function isClassLikeMemberCompletion(symbol, location) { + // TODO: support JS files. + if (ts.isInJSFile(location)) { + return false; + } + // Completion symbol must be for a class member. + var memberFlags = 106500 /* ClassMember */ + & 900095 /* EnumMemberExcludes */; + /* In + `class C { + | + }` + `location` is a class-like declaration. + In + `class C { + m| + }` + `location` is an identifier, + `location.parent` is a class element declaration, + and `location.parent.parent` is a class-like declaration. + In + `abstract class C { + abstract + abstract m| + }` + `location` is a syntax list (with modifiers as children), + and `location.parent` is a class-like declaration. + */ + return !!(symbol.flags & memberFlags) && + (ts.isClassLike(location) || + (location.parent && + location.parent.parent && + ts.isClassElement(location.parent) && + location === location.parent.name && + ts.isClassLike(location.parent.parent)) || + (location.parent && + ts.isSyntaxList(location) && + ts.isClassLike(location.parent))); + } + function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken) { + var classLikeDeclaration = ts.findAncestor(location, ts.isClassLike); + if (!classLikeDeclaration) { + return { insertText: name }; + } + var isSnippet; + var insertText = name; + var checker = program.getTypeChecker(); + var sourceFile = location.getSourceFile(); + var printer = createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target, + omitTrailingSemicolon: false, + newLine: ts.getNewLineKind(ts.getNewLineCharacter(options, ts.maybeBind(host, host.getNewLine))), + }); + var importAdder = ts.codefix.createImportAdder(sourceFile, program, preferences, host); + var body; + if (preferences.includeCompletionsWithSnippetText) { + isSnippet = true; + // We are adding a tabstop (i.e. `$0`) in the body of the suggested member, + // if it has one, so that the cursor ends up in the body once the completion is inserted. + // Note: this assumes we won't have more than one body in the completion nodes, which should be the case. + var emptyStatement = ts.factory.createExpressionStatement(ts.factory.createIdentifier("")); + ts.setSnippetElement(emptyStatement, { kind: 0 /* TabStop */, order: 0 }); + body = ts.factory.createBlock([emptyStatement], /* multiline */ true); + } + else { + body = ts.factory.createBlock([], /* multiline */ true); + } + var modifiers = 0 /* None */; + // Whether the suggested member should be abstract. + // e.g. in `abstract class C { abstract | }`, we should offer abstract method signatures at position `|`. + // Note: We are relying on checking if the context token is `abstract`, + // since other visibility modifiers (e.g. `protected`) should come *before* `abstract`. + // However, that is not true for the e.g. `override` modifier, so this check has its limitations. + var isAbstract = contextToken && isModifierLike(contextToken) === 126 /* AbstractKeyword */; + var completionNodes = []; + ts.codefix.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { program: program, host: host }, preferences, importAdder, + // `addNewNodeForMemberSymbol` calls this callback function for each new member node + // it adds for the given member symbol. + // We store these member nodes in the `completionNodes` array. + // Note: there might be: + // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; + // - One node; + // - More than one node if the member is overloaded (e.g. a method with overload signatures). + function (node) { + var requiredModifiers = 0 /* None */; + if (isAbstract) { + requiredModifiers |= 128 /* Abstract */; + } + if (ts.isClassElement(node) + && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node) === 1 /* NeedsOverride */) { + requiredModifiers |= 16384 /* Override */; + } + var presentModifiers = 0 /* None */; + if (!completionNodes.length) { + // Omit already present modifiers from the first completion node/signature. + if (contextToken) { + presentModifiers = getPresentModifiers(contextToken); + } + // Keep track of added missing required modifiers and modifiers already present. + // This is needed when we have overloaded signatures, + // so this callback will be called for multiple nodes/signatures, + // and we need to make sure the modifiers are uniform for all nodes/signatures. + modifiers = node.modifierFlagsCache | requiredModifiers | presentModifiers; + } + node = ts.factory.updateModifiers(node, modifiers & (~presentModifiers)); + completionNodes.push(node); + }, body, 2 /* Property */, isAbstract); + if (completionNodes.length) { + insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + } + return { insertText: insertText, isSnippet: isSnippet, importAdder: importAdder }; + } + function getPresentModifiers(contextToken) { + var modifiers = 0 /* None */; + var contextMod; + /* + Cases supported: + In + `class C { + public abstract | + }` + `contextToken` is ``abstract`` (as an identifier), + `contextToken.parent` is property declaration, + `location` is class declaration ``class C { ... }``. + In + `class C { + protected override m| + }` + `contextToken` is ``override`` (as a keyword), + `contextToken.parent` is property declaration, + `location` is identifier ``m``, + `location.parent` is property declaration ``protected override m``, + `location.parent.parent` is class declaration ``class C { ... }``. + */ + if (contextMod = isModifierLike(contextToken)) { + modifiers |= ts.modifierToFlag(contextMod); + } + if (ts.isPropertyDeclaration(contextToken.parent)) { + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + } + return modifiers; } - function originToCompletionEntryData(origin) { + function isModifierLike(node) { + if (ts.isModifier(node)) { + return node.kind; + } + if (ts.isIdentifier(node) && node.originalKeywordKind && ts.isModifierKind(node.originalKeywordKind)) { + return node.originalKeywordKind; + } + return undefined; + } + function createSnippetPrinter(printerOptions) { + var printer = ts.createPrinter(printerOptions); + var baseWriter = ts.createTextWriter(ts.getNewLineCharacter(printerOptions)); + var writer = __assign(__assign({}, baseWriter), { write: function (s) { return baseWriter.write(ts.escapeSnippetText(s)); }, nonEscapingWrite: baseWriter.write, writeLiteral: function (s) { return baseWriter.writeLiteral(ts.escapeSnippetText(s)); }, writeStringLiteral: function (s) { return baseWriter.writeStringLiteral(ts.escapeSnippetText(s)); }, writeSymbol: function (s, symbol) { return baseWriter.writeSymbol(ts.escapeSnippetText(s), symbol); }, writeParameter: function (s) { return baseWriter.writeParameter(ts.escapeSnippetText(s)); }, writeComment: function (s) { return baseWriter.writeComment(ts.escapeSnippetText(s)); }, writeProperty: function (s) { return baseWriter.writeProperty(ts.escapeSnippetText(s)); } }); return { + printSnippetList: printSnippetList, + }; + /* Snippet-escaping version of `printer.printList`. */ + function printSnippetList(format, list, sourceFile) { + writer.clear(); + printer.writeList(format, list, sourceFile, writer); + return writer.getText(); + } + } + function originToCompletionEntryData(origin) { + var ambientModuleName = origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name); + var isPackageJsonImport = origin.isFromPackageJson ? true : undefined; + if (originIsResolvedExport(origin)) { + var resolvedData = { + exportName: origin.exportName, + moduleSpecifier: origin.moduleSpecifier, + ambientModuleName: ambientModuleName, + fileName: origin.fileName, + isPackageJsonImport: isPackageJsonImport, + }; + return resolvedData; + } + var unresolvedData = { exportName: origin.exportName, + exportMapKey: origin.exportMapKey, fileName: origin.fileName, ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), isPackageJsonImport: origin.isFromPackageJson ? true : undefined, - moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, }; + return unresolvedData; + } + function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) { + var isDefaultExport = data.exportName === "default" /* Default */; + var isFromPackageJson = !!data.isPackageJsonImport; + if (completionEntryDataIsResolved(data)) { + var resolvedOrigin = { + kind: 32 /* ResolvedExport */, + exportName: data.exportName, + moduleSpecifier: data.moduleSpecifier, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return resolvedOrigin; + } + var unresolvedOrigin = { + kind: 4 /* Export */, + exportName: data.exportName, + exportMapKey: data.exportMapKey, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return unresolvedOrigin; } function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, contextToken, origin, useSemicolons, options, preferences) { var _a, _b, _c; @@ -128305,10 +128876,10 @@ var ts; var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? ts.tokenToString(151 /* TypeKeyword */) + " " : ""; var suffix = useSemicolons ? ";" : ""; switch (importKind) { - case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; - case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; - case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; - case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + ts.escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; } } function quotePropertyName(sourceFile, preferences, name) { @@ -128332,11 +128903,12 @@ var ts; return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { var _a; var start = ts.timestamp(); var variableDeclaration = getVariableDeclaration(location); var useSemicolons = ts.probablyUsesSemicolons(sourceFile); + var typeChecker = program.getTypeChecker(); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. @@ -128352,7 +128924,7 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var sortTextId = (_a = symbolToSortTextIdMap === null || symbolToSortTextIdMap === void 0 ? void 0 : symbolToSortTextIdMap[ts.getSymbolId(symbol)]) !== null && _a !== void 0 ? _a : 11 /* LocationPriority */; var sortText = (isDeprecated(symbol, typeChecker) ? 8 /* DeprecatedOffset */ + sortTextId : sortTextId).toString(); - var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); + var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind); if (!entry) { continue; } @@ -128445,11 +129017,13 @@ var ts; if (entryId.data) { var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); if (autoImport) { + var _a = getRelevantTokens(position, sourceFile), contextToken_1 = _a.contextToken, previousToken_1 = _a.previousToken; return { type: "symbol", symbol: autoImport.symbol, location: ts.getTouchingPropertyName(sourceFile, position), - previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + previousToken: previousToken_1, + contextToken: contextToken_1, isJsxInitializer: false, isTypeOnlyLocation: false, origin: autoImport.origin, @@ -128464,7 +129038,7 @@ var ts; if (completionData.kind !== 0 /* Data */) { return { type: "request", request: completionData }; } - var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, contextToken = completionData.contextToken, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; var literal = ts.find(literals, function (l) { return completionNameForLiteral(sourceFile, preferences, l) === entryId.name; }); if (literal !== undefined) return { type: "literal", literal: literal }; @@ -128475,15 +129049,15 @@ var ts; return ts.firstDefined(symbols, function (symbol, index) { var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); - return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + return info && info.name === entryId.name && (entryId.source === CompletionSource.ClassMemberSnippet && symbol.flags & 106500 /* ClassMember */ || getSourceFromOrigin(origin) === entryId.source) + ? { type: "symbol", symbol: symbol, location: location, origin: origin, contextToken: contextToken, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - var name = entryId.name; + var name = entryId.name, source = entryId.source, data = entryId.data; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); @@ -128507,8 +129081,8 @@ var ts; } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, contextToken_2 = symbolCompletion.contextToken, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken_2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -128537,21 +129111,34 @@ var ts; return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source) { if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { - var _a = getRelevantTokens(position, sourceFile), contextToken = _a.contextToken, previousToken_1 = _a.previousToken; - if (previousToken_1 && getImportStatementCompletionInfo(contextToken || previousToken_1).replacementNode) { + var _a = getRelevantTokens(position, sourceFile), contextToken_3 = _a.contextToken, previousToken_2 = _a.previousToken; + if (previousToken_2 && getImportStatementCompletionInfo(contextToken_3 || previousToken_2).replacementNode) { // Import statement completion: 'import c|' return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; } } + if (source === CompletionSource.ClassMemberSnippet) { + var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken).importAdder; + if (importAdder) { + var changes = ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, importAdder.writeFixes); + return { + sourceDisplay: undefined, + codeActions: [{ + changes: changes, + description: ts.diagnosticToString([ts.Diagnostics.Includes_imports_of_types_referenced_by_0, name]), + }], + }; + } + } if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { return { codeActions: undefined, sourceDisplay: undefined }; } var checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); var moduleSymbol = origin.moduleSymbol; - var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _b = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; + var targetSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _b = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; ts.Debug.assert(!(data === null || data === void 0 ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -129063,6 +129650,7 @@ var ts; } } function addPropertySymbol(symbol, insertAwait, insertQuestionDot) { + var _a; // For a computed property with an accessible name like `Symbol.iterator`, // we'll add a completion for the *name* `Symbol` instead of for the property. // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. @@ -129076,19 +129664,33 @@ var ts; var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + if (!moduleSymbol || + !ts.isExternalModuleSymbol(moduleSymbol) || + typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) { symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; } else { - var origin = { - kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), - moduleSymbol: moduleSymbol, - isDefaultExport: false, - symbolName: firstAccessibleSymbol.name, - exportName: firstAccessibleSymbol.name, - fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, - }; - symbolToOriginInfoMap[index] = origin; + var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; + var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + exportKind: 0 /* Named */, + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol: moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, + }], sourceFile, program, host, preferences) || {}).moduleSpecifier; + if (moduleSpecifier) { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: fileName, + moduleSpecifier: moduleSpecifier, + }; + symbolToOriginInfoMap[index] = origin; + } } } else if (preferences.includeCompletionsWithInsertText) { @@ -129245,11 +129847,11 @@ var ts; // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; - // If already using ES6 modules, OK to continue using them. + // If already using ES modules, OK to continue using them. if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + if (ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. return ts.programContainsModules(program); @@ -129324,7 +129926,7 @@ var ts; var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, preferences, !!importCompletionNode, function (context) { - exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule) { + exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule, exportMapKey) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) return; if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) @@ -129349,6 +129951,7 @@ var ts; kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, moduleSpecifier: moduleSpecifier, symbolName: symbolName, + exportMapKey: exportMapKey, exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, fileName: exportInfo_1.moduleFileName, isDefaultExport: isDefaultExport, @@ -129430,8 +130033,9 @@ var ts; function isNewIdentifierDefinitionLocation() { if (contextToken) { var containingNodeKind = contextToken.parent.kind; + var tokenKind = keywordForNode(contextToken); // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(contextToken)) { + switch (tokenKind) { case 27 /* CommaToken */: return containingNodeKind === 207 /* CallExpression */ // func( a, | || containingNodeKind === 170 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ @@ -129466,10 +130070,14 @@ var ts; return containingNodeKind === 222 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: return containingNodeKind === 232 /* TemplateSpan */; // `aa ${10} dd ${| - case 123 /* PublicKeyword */: - case 121 /* PrivateKeyword */: - case 122 /* ProtectedKeyword */: - return containingNodeKind === 166 /* PropertyDeclaration */; // class A{ public | + case 131 /* AsyncKeyword */: + return containingNodeKind === 168 /* MethodDeclaration */ // const obj = { async c|() + || containingNodeKind === 295 /* ShorthandPropertyAssignment */; // const obj = { async c| + case 41 /* AsteriskToken */: + return containingNodeKind === 168 /* MethodDeclaration */; // const obj = { * c| + } + if (isClassMemberCompletionKeyword(tokenKind)) { + return true; } } return false; @@ -130172,18 +130780,7 @@ var ts; return undefined; var isDefaultExport = data.exportName === "default" /* Default */; symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; - return { - symbol: symbol, - origin: { - kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, - moduleSymbol: moduleSymbol, - symbolName: name, - isDefaultExport: isDefaultExport, - exportName: data.exportName, - fileName: data.fileName, - isFromPackageJson: !!data.isPackageJsonImport, - } - }; + return { symbol: symbol, origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) }; } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; @@ -132564,7 +133161,7 @@ var ts; result = references; continue; } - var _loop_4 = function (entry) { + var _loop_5 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -132596,7 +133193,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_4(entry); + _loop_5(entry); } } return result; @@ -134574,7 +135171,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -134606,7 +135203,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } } function combineNormal(pathA, pathB) { @@ -135543,7 +136140,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_7 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -135555,7 +136152,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_6(sourceFile); + _loop_7(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -137559,15 +138156,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_7 = function (start) { + var _loop_8 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_2 = _loop_7(start); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(start); + if (typeof state_3 === "object") + return state_3.value; } return -1; } @@ -138230,6 +138827,7 @@ var ts; return false; } } + Rename.nodeIsEligibleForRename = nodeIsEligibleForRename; })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); /* @internal */ @@ -138945,7 +139543,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_8 = function (n) { + var _loop_9 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -138955,9 +139553,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_3 = _loop_8(n); - if (typeof state_3 === "object") - return state_3.value; + var state_4 = _loop_9(n); + if (typeof state_4 === "object") + return state_4.value; } return undefined; } @@ -139549,10 +140147,12 @@ var ts; program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; var checker = program.getTypeChecker(); - if (sourceFile.commonJsModuleIndicator && - (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + var isCommonJSFile = sourceFile.impliedNodeFormat === ts.ModuleKind.CommonJS || ts.fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]); + if (!isCommonJSFile && + sourceFile.commonJsModuleIndicator && + (ts.programContainsEsModules(program) || ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { - diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); visitedNestedConvertibleFunctions.clear(); @@ -139601,7 +140201,7 @@ var ts; } } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; - // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + // convertToEsModule only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { @@ -140528,7 +141128,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -140547,7 +141147,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -144215,7 +144815,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_10 = function (sourceFile, node) { + var _loop_11 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -144228,7 +144828,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_10(sourceFile, node); + _loop_11(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -144287,14 +144887,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_11 = function (i) { + var _loop_12 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_11(i); + _loop_12(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -144372,7 +144972,7 @@ var ts; /** Note: output node may be mutated input node. */ function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = createWriter(newLineCharacter); - var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + var newLine = ts.getNewLineKind(newLineCharacter); ts.createPrinter({ newLine: newLine, neverAsciiEscape: true, @@ -144837,21 +145437,16 @@ var ts; (function (codefix) { var errorCodeToFixes = ts.createMultiMap(); var fixIdToRegistration = new ts.Map(); - function diagnosticToString(diag) { - return ts.isArray(diag) - ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) - : ts.getLocaleSpecificMessage(diag); - } function createCodeFixActionWithoutFixAll(fixName, changes, description) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, fixAllDescription && ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { @@ -145198,7 +145793,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_12 = function (identifier) { + var _loop_13 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -145231,7 +145826,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_12(identifier); + _loop_13(identifier); } return initializers && { initializers: initializers, @@ -145522,9 +146117,6 @@ var ts; }); function makeChange(changeTracker, sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (!ts.isIdentifier(token)) { - return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.Debug.formatSyntaxKind(token.kind)); - } var param = token.parent; if (!ts.isParameter(param)) { return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.Debug.formatSyntaxKind(token.kind)); @@ -145532,9 +146124,10 @@ var ts; var i = param.parent.parameters.indexOf(param); ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.factory.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); - changeTracker.replaceNode(sourceFile, token, replacement); + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -146114,7 +146707,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 131 /* AsyncKeyword */, options); - var _loop_13 = function (returnStatement) { + var _loop_14 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -146136,9 +146729,9 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_4 = _loop_13(returnStatement); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_14(returnStatement); + if (typeof state_5 === "object") + return state_5.value; } } function getReturnStatementsWithPromiseHandlers(body, checker) { @@ -146795,11 +147388,11 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code], getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); + var moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; @@ -146808,7 +147401,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEsModule", changes, ts.Diagnostics.Convert_to_ES_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -146832,7 +147425,7 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: new ts.Set() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); @@ -146965,7 +147558,7 @@ var ts; // `const a = require("b").c` --> `import { c as a } from "./b"; return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid syntax form " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid syntax form " + name.kind); } } function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { @@ -147150,7 +147743,7 @@ var ts; case 79 /* Identifier */: return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid name kind " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid name kind " + name.kind); } } /** @@ -147470,7 +148063,11 @@ var ts; } function doChange(changes, sourceFile, _a) { var container = _a.container, typeNode = _a.typeNode, constraint = _a.constraint, name = _a.name; - changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode(/*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), /*nameType*/ undefined, /*questionToken*/ undefined, typeNode)); + changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode( + /*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), + /*nameType*/ undefined, + /*questionToken*/ undefined, typeNode, + /*members*/ undefined)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -147608,7 +148205,7 @@ var ts; var addToExisting = new ts.Map(); /** Use `getNewImportEntry` for access */ var newImports = new ts.Map(); - return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; + return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes, hasFixes: hasFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start, useAutoImportProvider); if (!info || !info.fixes.length) @@ -147759,6 +148356,9 @@ var ts; ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); } } + function hasFixes() { + return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; + } } // Sorted with the preferred fix coming first. var ImportFixKind; @@ -147778,11 +148378,11 @@ var ts; AddAsTypeOnly[AddAsTypeOnly["Required"] = 2] = "Required"; AddAsTypeOnly[AddAsTypeOnly["NotAllowed"] = 4] = "NotAllowed"; })(AddAsTypeOnly || (AddAsTypeOnly = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] - : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); + ? [getSymbolExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] + : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); var fix = ts.Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); @@ -147820,7 +148420,7 @@ var ts; } } } - function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { + function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { @@ -147833,12 +148433,12 @@ var ts; return; } var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: defaultInfo.exportKind, targetFlags: ts.skipAlias(defaultInfo.symbol, checker).flags, isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (exported.name === symbolName && checker.getMergedSymbol(ts.skipAlias(exported, checker)) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: exported, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: 0 /* Named */, targetFlags: ts.skipAlias(exported, checker).flags, isFromPackageJson: isFromPackageJson }); } } @@ -148089,12 +148689,14 @@ var ts; } var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; return fixes.reduce(function (best, fix) { + // Takes true branch of conditional if `fix` is better than `best` return compareModuleSpecifiers(fix, best, sourceFile, program, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; }); } + /** @returns `Comparison.LessThan` if `a` is better than `b`. */ function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { - return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + return ts.compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } @@ -148191,9 +148793,12 @@ var ts; })); return { fixes: fixes, symbolName: symbolName }; } + function jsxModeNeedsExplicitImport(jsx) { + return jsx === 2 /* React */ || jsx === 3 /* ReactNative */; + } function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -148762,6 +149367,7 @@ var ts; ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, @@ -149180,7 +149786,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_14 = function (info) { + var _loop_15 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -149207,7 +149813,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_14(info); + _loop_15(info); } }); })); @@ -150742,7 +151348,8 @@ var ts; insertBefore = ts.findChildOfKind(containingFunction, 98 /* FunctionKeyword */, sourceFile); break; case 213 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + var kind = containingFunction.typeParameters ? 29 /* LessThanToken */ : 20 /* OpenParenToken */; + insertBefore = ts.findChildOfKind(containingFunction, kind, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -151814,7 +152421,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_15 = function (i) { + var _loop_16 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -151823,7 +152430,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_15(i); + _loop_16(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); @@ -151962,7 +152569,7 @@ var ts; 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, sourceFile, context, preferences, importAdder, addClassElement); + addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /* body */ undefined); } } } @@ -151974,10 +152581,19 @@ var ts; }; } codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; - /** - * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. - */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement) { + var PreserveOptionalFlags; + (function (PreserveOptionalFlags) { + PreserveOptionalFlags[PreserveOptionalFlags["Method"] = 1] = "Method"; + PreserveOptionalFlags[PreserveOptionalFlags["Property"] = 2] = "Property"; + PreserveOptionalFlags[PreserveOptionalFlags["All"] = 3] = "All"; + })(PreserveOptionalFlags = codefix.PreserveOptionalFlags || (codefix.PreserveOptionalFlags = {})); + /** + * `addClassElement` will not be called if we can't figure out a representation for `symbol` in `enclosingDeclaration`. + * @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional, isAmbient) { + if (preserveOptional === void 0) { preserveOptional = 3 /* All */; } + if (isAmbient === void 0) { isAmbient = false; } var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -151990,7 +152606,7 @@ var ts; var modifiers = visibilityModifier ? ts.factory.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); - var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); + var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */) || isAmbient; var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { case 165 /* PropertySignature */: @@ -152005,7 +152621,7 @@ var ts; } } addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* Property */) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 171 /* GetAccessor */: @@ -152026,14 +152642,14 @@ var ts; var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -152054,7 +152670,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1, "One declaration implies one signature"); var signature = signatures[0]; - outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : body || createStubbedMethodBody(quotePreference)); break; } for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) { @@ -152065,21 +152681,22 @@ var ts; if (!ambient) { if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(quotePreference, signature, modifiers, name, createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, body || createStubbedMethodBody(quotePreference)); } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional && !!(preserveOptional & 1 /* Method */), modifiers, quotePreference, body)); } } break; } function outputMethod(quotePreference, signature, modifiers, name, body) { - var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder); + var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional && !!(preserveOptional & 1 /* Method */), enclosingDeclaration, importAdder); if (method) addClassElement(method); } } + codefix.addNewNodeForMemberSymbol = addNewNodeForMemberSymbol; function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { var program = context.program; var checker = program.getTypeChecker(); @@ -152217,7 +152834,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -152248,7 +152865,7 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, body); } function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { if (ts.length(signatures)) { @@ -152256,10 +152873,10 @@ var ts; return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); } } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(quotePreference)); + /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { return createStubbedBody(ts.Diagnostics.Method_not_implemented.message, quotePreference); @@ -153064,7 +153681,8 @@ var ts; var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.factory.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); var mappedIntersectionType = ts.factory.createMappedTypeNode(ts.hasEffectiveReadonlyModifier(indexSignature) ? ts.factory.createModifier(144 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, - /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type); + /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type, + /*members*/ undefined); var intersectionType = ts.factory.createIntersectionTypeNode(__spreadArray(__spreadArray(__spreadArray([], ts.getAllSuperTypeNodes(container), true), [ mappedIntersectionType ], false), (otherMembers.length ? [ts.factory.createTypeLiteralNode(otherMembers)] : ts.emptyArray), true)); @@ -153740,7 +154358,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_16 = function (element) { + var _loop_17 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -153757,7 +154375,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_16(element); + _loop_17(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { @@ -155612,7 +156230,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_18 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -155652,7 +156270,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_18(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -156307,17 +156925,17 @@ var ts; deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } - var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var useEsModuleSyntax = !!oldFile.externalModuleIndicator; var quotePreference = ts.getQuotePreference(oldFile, preferences); - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEsModuleSyntax, quotePreference); if (importsFromNewFile) { ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference); - var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax); + var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference); + var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); if (imports.length && body.length) { return __spreadArray(__spreadArray(__spreadArray(__spreadArray([], prologueDirectives, true), imports, true), [ 4 /* NewLineTrivia */ @@ -156341,10 +156959,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_18 = function (sourceFile) { + var _loop_19 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_19 = function (statement) { + var _loop_20 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -156366,12 +156984,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_19(statement); + _loop_20(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_18(sourceFile); + _loop_19(sourceFile); } } function getNamespaceLikeImport(node) { @@ -156564,7 +157182,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -156589,7 +157207,7 @@ var ts; continue; var top = getTopLevelDeclarationStatement(decl); if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEs6ModuleSyntax); + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); } if (ts.hasSyntacticModifier(decl, 512 /* Default */)) { oldFileDefault = name; @@ -156599,7 +157217,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEsModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -157735,7 +158353,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -157764,7 +158382,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_20(i); + _loop_21(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -159526,6 +160144,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); + if (!ts.Rename.nodeIsEligibleForRename(node)) + return undefined; if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; return [openingElement, closingElement].map(function (node) { @@ -164292,6 +164912,10 @@ var ts; this.hasAddedOrRemovedSymlinks = true; } }; + /* @internal */ + Project.prototype.onDiscoveredSymlink = function () { + this.hasAddedOrRemovedSymlinks = true; + }; /** * Updates set of files that contribute to this project * @returns: true if set of files in the project stays the same and false - otherwise. @@ -170624,11 +171248,13 @@ var ts; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file)); - if (!simplifiedResult) - return locations; var defaultProject = this.getDefaultProject(args); var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.checkDefined(this.projectService.getScriptInfo(file))); + if (!renameInfo.canRename) + return simplifiedResult ? { info: renameInfo, locs: [] } : []; + var locations = combineProjectOutputForRenameLocations(projects, defaultProject, { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file)); + if (!simplifiedResult) + return locations; return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; Session.prototype.mapRenameInfo = function (info, scriptInfo) { @@ -174306,7 +174932,7 @@ var ts; }; // Do this after sys has been set as findArguments is going to work only then var sys = server.createWebSystem(webHost, args, function () { return server.findArgument("--executingFilePath") || location + ""; }); - ts.sys = sys; + ts.setSys(sys); var localeStr = server.findArgument("--locale"); if (localeStr) { ts.validateLocaleAndSetLanguage(localeStr, sys); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 1a806cfdfa8ed..4c259d793d199 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -973,6 +973,8 @@ declare namespace ts { readonly nameType?: TypeNode; readonly questionToken?: QuestionToken | PlusToken | MinusToken; readonly type?: TypeNode; + /** Used only to produce grammar errors */ + readonly members?: NodeArray; } export interface LiteralTypeNode extends TypeNode { readonly kind: SyntaxKind.LiteralType; @@ -3420,8 +3422,8 @@ declare namespace ts { updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; - updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; + updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode; @@ -4040,6 +4042,7 @@ declare namespace ts { readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; + readonly includeCompletionsWithClassMemberSnippets?: boolean; readonly allowIncompleteCompletions?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -6367,23 +6370,28 @@ declare namespace ts { isIncomplete?: true; entries: CompletionEntry[]; } - interface CompletionEntryData { - /** The file name declaring the export's module symbol, if it was an external module */ - fileName?: string; - /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ - ambientModuleName?: string; - /** True if the export was found in the package.json AutoImportProvider */ - isPackageJsonImport?: true; + interface CompletionEntryDataAutoImport { /** * The name of the property or export in the module's symbol table. Differs from the completion name * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. */ exportName: string; - /** - * Set for auto imports with eagerly resolved module specifiers. - */ moduleSpecifier?: string; + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; } + interface CompletionEntryDataUnresolved extends CompletionEntryDataAutoImport { + /** The key in the `ExportMapCache` where the completion entry's `SymbolExportInfo[]` is found */ + exportMapKey: string; + } + interface CompletionEntryDataResolved extends CompletionEntryDataAutoImport { + moduleSpecifier: string; + } + type CompletionEntryData = CompletionEntryDataUnresolved | CompletionEntryDataResolved; interface CompletionEntry { name: string; kind: ScriptElementKind; @@ -9530,6 +9538,13 @@ declare namespace ts.server.protocol { * values, with insertion text to replace preceding `.` tokens with `?.`. */ readonly includeAutomaticOptionalChainCompletions?: boolean; + /** + * If enabled, completions for class members (e.g. methods and properties) will include + * a whole declaration for the member. + * E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of + * `class A { foo }`. + */ + readonly includeCompletionsWithClassMemberSnippets?: boolean; readonly allowIncompleteCompletions?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -10774,9 +10789,9 @@ declare namespace ts { /** @deprecated Use `factory.updateIndexedAccessTypeNode` or the factory supplied by your transformation context instead. */ const updateIndexedAccessTypeNode: (node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) => IndexedAccessTypeNode; /** @deprecated Use `factory.createMappedTypeNode` or the factory supplied by your transformation context instead. */ - const createMappedTypeNode: (readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined) => MappedTypeNode; + const createMappedTypeNode: (readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined) => MappedTypeNode; /** @deprecated Use `factory.updateMappedTypeNode` or the factory supplied by your transformation context instead. */ - const updateMappedTypeNode: (node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined) => MappedTypeNode; + const updateMappedTypeNode: (node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined) => MappedTypeNode; /** @deprecated Use `factory.createLiteralTypeNode` or the factory supplied by your transformation context instead. */ const createLiteralTypeNode: (literal: LiteralExpression | BooleanLiteral | PrefixUnaryExpression | NullLiteral) => LiteralTypeNode; /** @deprecated Use `factory.updateLiteralTypeNode` or the factory supplied by your transformation context instead. */ diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 0f2779eb85009..a51a6d46f6588 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -21,7 +21,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -294,7 +294,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.5.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -323,21 +323,24 @@ var ts; return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; - })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { + })(NativeCollections || (NativeCollections = {})); + /* @internal */ + ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); + /* @internal */ + ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); + /* @internal */ function getCollectionImplementation(name, nativeFactory, shimFactory) { var _a; // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it. - var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator); + var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); if (constructor) return constructor; throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation."); } - ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); - ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { function getIterator(iterable) { if (iterable) { if (isArray(iterable)) @@ -2742,6 +2745,10 @@ var ts; return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } Debug.formatSyntaxKind = formatSyntaxKind; + function formatSnippetKind(kind) { + return formatEnum(kind, ts.SnippetKind, /*isFlags*/ false); + } + Debug.formatSnippetKind = formatSnippetKind; function formatNodeFlags(flags) { return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true); } @@ -4658,6 +4665,13 @@ var ts; ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ + var MemberOverrideStatus; + (function (MemberOverrideStatus) { + MemberOverrideStatus[MemberOverrideStatus["Ok"] = 0] = "Ok"; + MemberOverrideStatus[MemberOverrideStatus["NeedsOverride"] = 1] = "NeedsOverride"; + MemberOverrideStatus[MemberOverrideStatus["HasInvalidOverride"] = 2] = "HasInvalidOverride"; + })(MemberOverrideStatus = ts.MemberOverrideStatus || (ts.MemberOverrideStatus = {})); + /* @internal */ var UnionReduction; (function (UnionReduction) { UnionReduction[UnionReduction["None"] = 0] = "None"; @@ -5053,8 +5067,6 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable"; - /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 468598819] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask"; @@ -5067,6 +5079,10 @@ var ts; TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["IncludesInstantiable"] = 33554432] = "IncludesInstantiable"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check @@ -5306,7 +5322,7 @@ var ts; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - // Starting with node12, node's module resolver has significant departures from tranditional cjs resolution + // Starting with node12, node's module resolver has significant departures from traditional cjs resolution // to better support ecmascript modules and their use within node - more features are still being added, so // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12` // version-anchored resolution target @@ -5639,6 +5655,15 @@ var ts; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax + /* @internal */ + var SnippetKind; + (function (SnippetKind) { + SnippetKind[SnippetKind["TabStop"] = 0] = "TabStop"; + SnippetKind[SnippetKind["Placeholder"] = 1] = "Placeholder"; + SnippetKind[SnippetKind["Choice"] = 2] = "Choice"; + SnippetKind[SnippetKind["Variable"] = 3] = "Variable"; + })(SnippetKind = ts.SnippetKind || (ts.SnippetKind = {})); var EmitFlags; (function (EmitFlags) { EmitFlags[EmitFlags["None"] = 0] = "None"; @@ -7932,7 +7957,7 @@ var ts; } } function readDirectory(path, extensions, excludes, includes, depth) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve @@ -8017,6 +8042,11 @@ var ts; } return sys; })(); + /*@internal*/ + function setSys(s) { + ts.sys = s; + } + ts.setSys = setSys; if (ts.sys && ts.sys.getEnvironmentVariable) { setCustomPollingValues(ts.sys); ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) @@ -8327,6 +8357,7 @@ var ts; Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."), Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), + _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8868,6 +8899,9 @@ var ts; Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), 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}'."), @@ -8974,6 +9008,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), 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}'."), @@ -9526,6 +9561,8 @@ var ts; If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."), + A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."), + JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."), 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_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."), @@ -9581,7 +9618,7 @@ var ts; Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."), This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), @@ -9629,6 +9666,7 @@ var ts; Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"), Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), + Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), 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_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -9643,7 +9681,7 @@ var ts; 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"), + Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"), Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), @@ -19822,6 +19860,8 @@ var ts; case ts.ModuleKind.ES2020: case ts.ModuleKind.ES2022: case ts.ModuleKind.ESNext: + case ts.ModuleKind.Node12: + case ts.ModuleKind.NodeNext: return true; default: return false; @@ -20186,7 +20226,7 @@ var ts; } ts.getRegexFromPattern = getRegexFromPattern; /** @param path directory of the tsconfig.json */ - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -20200,9 +20240,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - if (directoryExists(basePath)) { - visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); - } + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -20307,10 +20345,14 @@ var ts; var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { case ".js" /* Js */: + case ".cjs" /* Cjs */: + case ".mjs" /* Mjs */: return 1 /* JS */; case ".jsx" /* Jsx */: return 2 /* JSX */; case ".ts" /* Ts */: + case ".cts" /* Cts */: + case ".mts" /* Mts */: return 3 /* TS */; case ".tsx" /* Tsx */: return 4 /* TSX */; @@ -20929,6 +20971,10 @@ var ts; return node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; + function escapeSnippetText(text) { + return text.replace(/\$/gm, "\\$"); + } + ts.escapeSnippetText = escapeSnippetText; })(ts || (ts = {})); /* @internal */ var ts; @@ -23086,24 +23132,26 @@ var ts; : node; } // @api - function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { + function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { var node = createBaseNode(194 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; node.questionToken = questionToken; node.type = type; + node.members = members && createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api - function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) { + function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) { return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type - ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node) + || node.members !== members + ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } // @api @@ -27130,6 +27178,25 @@ var ts; } } ts.moveEmitHelpers = moveEmitHelpers; + /** + * Gets the SnippetElement of a node. + */ + /* @internal */ + function getSnippetElement(node) { + var _a; + return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement; + } + ts.getSnippetElement = getSnippetElement; + /** + * Sets the SnippetElement of a node. + */ + /* @internal */ + function setSnippetElement(node, snippet) { + var emitNode = getOrCreateEmitNode(node); + emitNode.snippetElement = snippet; + return node; + } + ts.setSnippetElement = setSnippetElement; /* @internal */ function ignoreSourceNewlines(node) { getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */; @@ -29976,7 +30043,8 @@ var ts; visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) || + visitNodes(cbNode, cbNodes, node.members); case 195 /* LiteralType */: return visitNode(cbNode, node.literal); case 196 /* NamedTupleMember */: @@ -32110,7 +32178,10 @@ var ts; case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected); case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected); case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); - case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); + case 16 /* Parameters */: + return ts.isKeyword(token()) + ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_parameter_name, ts.tokenToString(token())) + : parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected); case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected); case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected); @@ -32866,8 +32937,9 @@ var ts; } var type = parseTypeAnnotation(); parseSemicolon(); + var members = parseList(4 /* TypeMembers */, parseTypeMember); parseExpected(19 /* CloseBraceToken */); - return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos); + return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } function parseTupleElementType() { var pos = getNodePos(); @@ -36154,16 +36226,21 @@ var ts; var pos = getNodePos(); parseExpected(129 /* AssertKeyword */); var openBracePosition = scanner.getTokenPos(); - parseExpected(18 /* OpenBraceToken */); - var multiLine = scanner.hasPrecedingLineBreak(); - var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); - if (!parseExpected(19 /* CloseBraceToken */)) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { - ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + if (parseExpected(18 /* OpenBraceToken */)) { + var multiLine = scanner.hasPrecedingLineBreak(); + var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); + if (!parseExpected(19 /* CloseBraceToken */)) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { + ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + } } + return finishNode(factory.createAssertClause(elements, multiLine), pos); + } + else { + var elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false); + return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos); } - return finishNode(factory.createAssertClause(elements, multiLine), pos); } function tokenAfterImportDefinitelyProducesImportDeclaration() { return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */; @@ -37058,8 +37135,9 @@ var ts; return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); - var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */ + || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference(); var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } @@ -38148,7 +38226,7 @@ var ts; var ts; (function (ts) { /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1 /* Preserve */, "react-native": 3 /* ReactNative */, @@ -38285,6 +38363,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: "false", }, { name: "excludeDirectories", @@ -38320,11 +38399,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, + defaultValueDescription: "false", }, { name: "help", shortName: "?", - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "watch", @@ -38334,6 +38415,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, + defaultValueDescription: "false", }, { name: "preserveWatchOutput", @@ -38341,7 +38423,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "listFiles", @@ -38354,7 +38436,8 @@ var ts; name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, - description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included + description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: "false", }, { name: "listEmittedFiles", @@ -38425,7 +38508,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, - description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it + description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: "false", }, { name: "locale", @@ -38470,6 +38554,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, + defaultValueDescription: "false", }, { name: "version", @@ -38478,6 +38563,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: "false", }, { name: "init", @@ -38485,6 +38571,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: "false", }, { name: "project", @@ -38502,7 +38589,8 @@ var ts; shortName: "b", showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: "false", }, { name: "showConfig", @@ -38510,7 +38598,8 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, - description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: "false", }, { name: "listFilesOnly", @@ -38519,7 +38608,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, isCommandLineOnly: true, - description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: "false", }, // Basic ts.targetOptionDeclaration, @@ -38639,7 +38729,6 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, transpileOptionValue: undefined, - defaultValueDescription: "n/a" }, { name: "outDir", @@ -38650,7 +38739,6 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files, - defaultValueDescription: "n/a" }, { name: "rootDir", @@ -38807,6 +38895,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: "false", }, { name: "alwaysStrict", @@ -38839,7 +38928,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined + description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: "false", }, { name: "noImplicitReturns", @@ -38855,21 +38945,24 @@ var ts; affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements + description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: "false", }, { name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Include_undefined_in_index_signature_results + description: ts.Diagnostics.Include_undefined_in_index_signature_results, + defaultValueDescription: "false", }, { name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: "false", }, { name: "noPropertyAccessFromIndexSignature", @@ -38885,6 +38978,8 @@ var ts; type: new ts.Map(ts.getEntries({ node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, + node12: ts.ModuleResolutionKind.Node12, + nodenext: ts.ModuleResolutionKind.NodeNext, })), affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, @@ -38976,7 +39071,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "allowUmdGlobalAccess", @@ -39025,7 +39120,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators + description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, + defaultValueDescription: "false", }, { name: "emitDecoratorMetadata", @@ -39033,7 +39129,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files + description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: "false", }, // Advanced { @@ -39076,7 +39173,6 @@ var ts; category: ts.Diagnostics.Backwards_Compatibility, paramType: ts.Diagnostics.FILE, transpileOptionValue: undefined, - defaultValueDescription: "n/a", description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead, }, { @@ -39157,6 +39253,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: "false", }, { name: "disableSizeLimit", @@ -39171,21 +39268,24 @@ var ts; type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects + description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: "false", }, { name: "disableSolutionSearching", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing + description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: "false", }, { name: "disableReferencedProjectLoad", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript + description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: "false", }, { name: "noImplicitUseStrict", @@ -39218,7 +39318,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "declarationDir", @@ -39229,7 +39329,6 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files, - defaultValueDescription: "n/a" }, { name: "skipLibCheck", @@ -39311,6 +39410,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: "false", }, { name: "keyofStringsOnly", @@ -39358,27 +39458,31 @@ var ts; shortName: "v", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "dry", shortName: "d", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "force", shortName: "f", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", } ]; /* @internal */ @@ -39391,10 +39495,12 @@ var ts; */ name: "enableAutoDiscovery", type: "boolean", + defaultValueDescription: "false", }, { name: "enable", type: "boolean", + defaultValueDescription: "false", }, { name: "include", @@ -39415,6 +39521,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", + defaultValueDescription: "false", }, ]; /*@internal*/ @@ -42687,11 +42794,15 @@ var ts; if (!scope || !scope.packageJsonContent.exports) { return undefined; } + if (typeof scope.packageJsonContent.name !== "string") { + return undefined; + } var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry - if (scope.packageJsonContent.name !== parts[1]) { + var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } - var trailingParts = parts.slice(2); + var trailingParts = parts.slice(nameParts.length); return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : "." + ts.directorySeparator + trailingParts.join(ts.directorySeparator), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { @@ -45830,6 +45941,7 @@ var ts; case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: case 172 /* SetAccessor */: + case 169 /* ClassStaticBlockDeclaration */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -47210,6 +47322,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isPropertyAccessible: isPropertyAccessible, getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration, + getMemberOverrideModifierStatus: getMemberOverrideModifierStatus, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -47453,6 +47566,21 @@ var ts; var enumRelation = new ts.Map(); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + // Extensions suggested for path imports when module resolution is node12 or higher. + // The first element of each tuple is the extension a file has. + // The second element of each tuple is the extension that should be used in a path import. + // e.g. if we want to import file `foo.mts`, we should write `import {} from "./foo.mjs". + var suggestedExtensions = [ + [".mts", ".mjs"], + [".ts", ".js"], + [".cts", ".cjs"], + [".mjs", ".mjs"], + [".js", ".js"], + [".cjs", ".cjs"], + [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], + [".jsx", ".jsx"], + [".json", ".json"], + ]; initializeTypeChecker(); return checker; function getJsxNamespace(location) { @@ -48169,11 +48297,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, issueSuggestions) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, issueSuggestions); + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, issueSuggestions) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { var _a, _b, _c; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; @@ -48500,7 +48628,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (issueSuggestions && suggestionCount < maximumSuggestionCount) { + if (suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -48509,7 +48637,9 @@ var ts; if (suggestion) { var suggestionName = symbolToString(suggestion); var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); - var message = isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; + var message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 + : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 + : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { @@ -48954,6 +49084,10 @@ var ts; function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === ts.ModuleKind.ESNext && targetMode === ts.ModuleKind.CommonJS; } + function isOnlyImportedAsDefault(usage) { + var usageMode = getUsageModeForExpression(usage); + return usageMode === ts.ModuleKind.ESNext && ts.endsWith(usage.text, ".json" /* Json */); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { var usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== undefined) { @@ -49004,8 +49138,9 @@ var ts; exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); + var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier); - if (!exportDefaultSymbol && !hasSyntheticDefault) { + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); @@ -49019,7 +49154,7 @@ var ts; reportNonDefaultExport(moduleSymbol, node); } } - else if (hasSyntheticDefault) { + else if (hasSyntheticDefault || hasDefaultOnly) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); @@ -49144,7 +49279,7 @@ var ts; var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); - if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } @@ -49503,7 +49638,7 @@ var ts; if (name.kind === 79 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true, false)); if (!symbol) { return getMergedSymbol(symbolFromJSPrototype); } @@ -49538,21 +49673,28 @@ var ts; var namespaceName = getFullyQualifiedName(namespace); var declarationName = ts.declarationNameToString(right); var suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); - var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); - var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); - var canSuggestTypeof = containingQualifiedName && !ts.isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (suggestionForNonexistentModule) { error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + return undefined; } - else if (canSuggestTypeof) { + var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); + var canSuggestTypeof = globalObjectType // <-- can't pull on types if global types aren't initialized yet + && (meaning & 788968 /* Type */) + && containingQualifiedName + && !ts.isTypeOfExpression(containingQualifiedName.parent) + && tryGetQualifiedNameAsValue(containingQualifiedName); + if (canSuggestTypeof) { error(containingQualifiedName, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.entityNameToString(containingQualifiedName)); + return undefined; } - else if (meaning & 1920 /* Namespace */ && exportedTypeSymbol && ts.isQualifiedName(name.parent)) { - error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); - } - else { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + if (meaning & 1920 /* Namespace */ && ts.isQualifiedName(name.parent)) { + var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); + if (exportedTypeSymbol) { + error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); + return undefined; + } } + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); } return undefined; } @@ -49654,7 +49796,7 @@ var ts; : undefined; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - var _a, _b, _c, _d, _e, _f; + var _a, _b, _c, _d, _e, _f, _g; if (isForAugmentation === void 0) { isForAugmentation = false; } if (ts.startsWith(moduleReference, "@types/")) { var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -49674,7 +49816,8 @@ var ts; ((_d = ts.findAncestor(location, ts.isExportDeclaration)) === null || _d === void 0 ? void 0 : _d.moduleSpecifier) || ((_e = (ts.isModuleDeclaration(location) ? location : location.parent && ts.isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)) === null || _e === void 0 ? void 0 : _e.name) || ((_f = (ts.isLiteralImportTypeNode(location) ? location : undefined)) === null || _f === void 0 ? void 0 : _f.argument.literal); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : undefined); // TODO: GH#18217 + var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -49687,6 +49830,9 @@ var ts; if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) { error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); } + if (mode === ts.ModuleKind.ESNext && compilerOptions.resolveJsonModule && resolvedModule.extension === ".json" /* Json */) { + error(errorNode, ts.Diagnostics.JSON_imports_are_experimental_in_ES_module_mode_imports); + } } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); @@ -49737,6 +49883,10 @@ var ts; } else { var tsExtension = ts.tryExtractTSExtension(moduleReference); + var isExtensionlessRelativePathImport = ts.pathIsRelative(moduleReference) && !ts.hasExtension(moduleReference); + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var resolutionIsNode12OrNext = moduleResolutionKind === ts.ModuleResolutionKind.Node12 || + moduleResolutionKind === ts.ModuleResolutionKind.NodeNext; if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension); @@ -49756,6 +49906,19 @@ var ts; ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } + else if (mode === ts.ModuleKind.ESNext && resolutionIsNode12OrNext && isExtensionlessRelativePathImport) { + var absoluteRef_1 = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(currentSourceFile.path)); + var suggestedExt = (_g = suggestedExtensions.find(function (_a) { + var actualExt = _a[0], _importExt = _a[1]; + return host.fileExists(absoluteRef_1 + actualExt); + })) === null || _g === void 0 ? void 0 : _g[1]; + if (suggestedExt) { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + } + else { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -49825,40 +49988,50 @@ var ts; error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } - if (ts.getESModuleInterop(compilerOptions)) { - var referenceParent = referencingLocation.parent; - if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || - ts.isImportCall(referenceParent)) { - var type = getTypeOfSymbol(symbol); + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var reference = ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier; + var type = getTypeOfSymbol(symbol); + var defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); + if (defaultOnlyType) { + return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); + } + if (ts.getESModuleInterop(compilerOptions)) { 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, ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier); - // 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 = new ts.Map(symbol.members); - if (symbol.exports) - result.exports = new ts.Map(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.indexInfos); - return result; + if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); + return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } } } } return symbol; } + /** + * Create a new symbol which has the module's type less the call and construct signatures + */ + function cloneTypeAsModuleType(symbol, moduleType, referenceParent) { + 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 = new ts.Map(symbol.members); + if (symbol.exports) + result.exports = new ts.Map(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.indexInfos); + return result; + } function hasExportAssignmentSymbol(moduleSymbol) { return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } @@ -49887,8 +50060,8 @@ var ts; if (exportEquals !== moduleSymbol) { var type = getTypeOfSymbol(exportEquals); if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { - getPropertiesOfType(type).forEach(function (symbol) { - cb(symbol, symbol.escapedName); + forEachPropertyOfType(type, function (symbol, escapedName) { + cb(symbol, escapedName); }); } } @@ -50220,12 +50393,15 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + if (isNamedMember(symbol, id)) { (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } + function isNamedMember(member, escapedName) { + return !isReservedMemberName(escapedName) && symbolIsValue(member); + } function getNamedOrIndexSignatureMembers(members) { var result = getNamedMembers(members); var index = getIndexSymbolFromSymbolTable(members); @@ -51100,7 +51276,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined; var templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), context); - var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode); + var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } @@ -57058,6 +57234,16 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function forEachPropertyOfType(type, action) { + type = getReducedApparentType(type); + if (type.flags & 3670016 /* StructuredType */) { + resolveStructuredTypeMembers(type).members.forEach(function (symbol, escapedName) { + if (isNamedMember(symbol, escapedName)) { + action(symbol, escapedName); + } + }); + } + } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { var list = obj.properties; return list.some(function (property) { @@ -57994,7 +58180,7 @@ var ts; return false; switch (node.kind) { case 79 /* Identifier */: - return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; case 166 /* PropertyDeclaration */: case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: @@ -59343,6 +59529,8 @@ var ts; // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { includes |= flags & 205258751 /* IncludesMask */; + if (flags & 465829888 /* Instantiable */) + includes |= 33554432 /* IncludesInstantiable */; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { @@ -59451,7 +59639,7 @@ var ts; var _loop_16 = function () { i--; var t = types[i]; - if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) { + if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { ts.orderedRemoveItemAt(types, i); } }; @@ -59556,7 +59744,7 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + var objectFlags = (includes & 36323363 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | (includes & 2097152 /* Intersection */ ? 33554432 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } @@ -60533,12 +60721,6 @@ var ts; } return type[cache] = type; } - function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { - var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); - var checkType = type.checkType; - var extendsType = type.extendsType; - return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); - } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -60847,6 +61029,10 @@ var ts; } return result; } + function isDistributionDependent(root) { + return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || + isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType)); + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -61646,7 +61832,9 @@ var ts; return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { if (!type.declaration.nameType) { - if (isArrayType(t)) { + var constraint = void 0; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && + (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, ts.or(isArrayType, isTupleType))) { return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); } if (isGenericTupleType(t)) { @@ -63186,13 +63374,12 @@ var ts; traceUnionsOrIntersectionsTooLarge(source, target); var result = 0 /* False */; var saveErrorInfo = captureErrorCalculationState(); - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { - result = getConstituentCount(source) * getConstituentCount(target) >= 4 ? - recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags) : - structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) { + // We skip caching when source or target is a union with no more than three constituents. + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + } + else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { + result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags); } if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { @@ -63649,19 +63836,19 @@ var ts; var maybeStart = maybeCount; maybeKeys[maybeCount] = id; maybeCount++; + var saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { sourceStack[sourceDepth] = source; sourceDepth++; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) + expandingFlags |= 1 /* Source */; } if (recursionFlags & 2 /* Target */) { targetStack[targetDepth] = target; targetDepth++; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) + expandingFlags |= 2 /* Target */; } - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) - expandingFlags |= 1 /* Source */; - if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) - expandingFlags |= 2 /* Target */; var originalHandler; var propagatingVarianceFlags = 0; if (outofbandVarianceMarkerHandler) { @@ -63685,13 +63872,13 @@ var ts; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } - expandingFlags = saveExpandingFlags; if (recursionFlags & 1 /* Source */) { sourceDepth--; } if (recursionFlags & 2 /* Target */) { targetDepth--; } + expandingFlags = saveExpandingFlags; if (result) { if (result === -1 /* True */ || (sourceDepth === 0 && targetDepth === 0)) { if (result === -1 /* True */ || result === 3 /* Maybe */) { @@ -63932,7 +64119,7 @@ var ts; originalErrorInfo = undefined; } } - else if (isGenericMappedType(target)) { + else if (isGenericMappedType(target) && relation !== identityRelation) { // Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`. var keysRemapped = !!target.declaration.nameType; var templateType = getTemplateTypeFromMappedType(target); @@ -63996,32 +64183,28 @@ var ts; } } else if (target.flags & 16777216 /* Conditional */) { - var c = target; - // Check if the conditional is always true or always false but still deferred for distribution purposes - var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); - var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); - // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, - // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when - // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, - // to which `{x: string | number, y: string | number}` isn't assignable) - var distributionMapper = void 0; - var checkVar = getActualTypeVariable(c.root.checkType); - if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { - var newParam = cloneTypeParameter(checkVar); - distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); - newParam.mapper = distributionMapper; - } - // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) - var expanding = isDeeplyNestedType(target, targetStack, targetDepth); - var localResult = expanding ? 3 /* Maybe */ : undefined; - if (skipTrue || expanding || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false))) { - if (!skipFalse && !expanding) { - localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); - } - } - if (localResult) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { resetErrorInfo(saveErrorInfo); - return localResult; + return 3 /* Maybe */; + } + var c = target; + // We check for a relationship to a conditional type target only when the conditional type has no + // 'infer' positions and is not distributive or is distributive but doesn't reference the check type + // parameter in either of the result types. + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) { + // Check if the conditional is always true or always false but still deferred for distribution purposes. + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + if (result = skipTrue ? -1 /* True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false)) { + result &= skipFalse ? -1 /* True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + } } } else if (target.flags & 134217728 /* TemplateLiteral */) { @@ -64033,8 +64216,7 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_9 = inferTypesFromTemplateLiteralType(source, target); - if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* True */; } } @@ -64092,33 +64274,34 @@ var ts; } } else if (source.flags & 16777216 /* Conditional */) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { + resetErrorInfo(saveErrorInfo); + return 3 /* Maybe */; + } if (target.flags & 16777216 /* Conditional */) { - // If one of the conditionals under comparison seems to be infinitely expanding, stop comparing it - back out, try - // the constraint, and failing that, give up trying to relate the two. This is the only way we can handle recursive conditional - // types, which might expand forever. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth) && !isDeeplyNestedType(target, targetStack, targetDepth)) { - // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if - // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, - // and Y1 is related to Y2. - var sourceParams = source.root.inferTypeParameters; - var sourceExtends = source.extendsType; - var mapper = void 0; - if (sourceParams) { - // If the source has infer type parameters, we instantiate them in the context of the target - var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); - sourceExtends = instantiateType(sourceExtends, ctx.mapper); - mapper = ctx.mapper; - } - if (isTypeIdenticalTo(sourceExtends, target.extendsType) && - (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { - if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + var sourceParams = source.root.inferTypeParameters; + var sourceExtends = source.extendsType; + var mapper = void 0; + if (sourceParams) { + // If the source has infer type parameters, we instantiate them in the context of the target + var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); + sourceExtends = instantiateType(sourceExtends, ctx.mapper); + mapper = ctx.mapper; + } + if (isTypeIdenticalTo(sourceExtends, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { + if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64133,17 +64316,13 @@ var ts; } } } - // We'll repeatedly decompose source side conditionals if they're recursive - check if we've already recured on the constraint a lot and, if so, bail - // on the comparison. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth)) { - // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` - // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). - var defaultConstraint = getDefaultConstraintOfConditionalType(source); - if (defaultConstraint) { - if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` + // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64232,9 +64411,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_10) { - return result_10; + var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_9) { + return result_9; } } } @@ -64306,13 +64485,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_11; + var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { + if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); + return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); } } } @@ -65252,14 +65431,15 @@ var ts; // `type A = null extends T ? [A>] : [T]` // has expanded into `[A>>>>>]` // in such cases we need to terminate the expansion, and we do so here. - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5) { + function isDeeplyNestedType(type, stack, depth, maxDepth) { + if (maxDepth === void 0) { maxDepth = 5; } + if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; for (var i = 0; i < depth; i++) { if (getRecursionIdentity(stack[i]) === identity_1) { count++; - if (count >= 5) { + if (count >= maxDepth) { return true; } } @@ -66000,7 +66180,8 @@ var ts; (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { var newName = "arg" + param.parent.parameters.indexOf(param); - errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + var typeName = ts.declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); return; } diagnostic = declaration.dotDotDotToken ? @@ -66394,6 +66575,10 @@ var ts; inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : undefined; } + function isTypeMatchedByTemplateLiteralType(source, target) { + var inferences = inferTypesFromTemplateLiteralType(source, target); + return !!inferences && ts.every(inferences, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); }); + } function getStringLikeTypeForType(type) { return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); } @@ -67170,17 +67355,16 @@ var ts; var inferredType = void 0; var signature = context.signature; if (signature) { - var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + var inferredCovariantType_1 = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - var inferredContravariantType = getContravariantInference(inference); // If we have both co- and contra-variant inferences, we prefer the contra-variant inference - // unless the co-variant inference is a subtype and not 'never'. - inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && - isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? - inferredCovariantType : inferredContravariantType; + // unless the co-variant inference is a subtype of some contra-variant inference and not 'never'. + inferredType = inferredCovariantType_1 && !(inferredCovariantType_1.flags & 131072 /* Never */) && + ts.some(inference.contraCandidates, function (t) { return isTypeSubtypeOf(inferredCovariantType_1, t); }) ? + inferredCovariantType_1 : getContravariantInference(inference); } - else if (inferredCovariantType) { - inferredType = inferredCovariantType; + else if (inferredCovariantType_1) { + inferredType = inferredCovariantType_1; } else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -67281,8 +67465,7 @@ var ts; if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), - /*excludeGlobals*/ false, - /*issueSuggestions*/ true) || unknownSymbol; + /*excludeGlobals*/ false) || unknownSymbol; } return links.resolvedSymbol; } @@ -67299,8 +67482,11 @@ var ts; function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 79 /* Identifier */: - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + if (!ts.isThisInTypeQuery(node)) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + } + // falls through case 108 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); case 229 /* NonNullExpression */: @@ -67480,8 +67666,9 @@ var ts; // constituent types keyed by the literal types of the property by that name in each constituent type. function getKeyPropertyName(unionType) { var types = unionType.types; - // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + // We only construct maps for unions with many non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */ || + ts.countWhere(types, function (t) { return !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */)); }) < 10) { return undefined; } if (unionType.keyPropertyName === undefined) { @@ -67514,7 +67701,7 @@ var ts; var keyPropertyName = getKeyPropertyName(unionType); var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 294 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); - var propType = propNode && getTypeOfExpression(propNode.initializer); + var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } function isOrContainsMatchingReference(source, target) { @@ -67930,7 +68117,7 @@ var ts; mapType(type, mapper); } function getConstituentCount(type) { - return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; + return type.flags & 1048576 /* Union */ ? type.types.length : 1; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -69428,7 +69615,7 @@ var ts; return parent.kind === 205 /* PropertyAccessExpression */ || parent.kind === 207 /* CallExpression */ && parent.expression === node || parent.kind === 206 /* ElementAccessExpression */ && parent.expression === node && - !(isGenericTypeWithoutNullableConstraint(type) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); + !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); @@ -70749,7 +70936,7 @@ var ts; return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 294 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -71304,6 +71491,10 @@ var ts; function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { + if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) { + return links.resolvedType = errorType; + } links.resolvedType = checkExpression(node.expression); // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. // (It needs to be bound at class evaluation time.) @@ -72773,7 +72964,7 @@ var ts; if (relatedInfo) { ts.addRelatedInfo(resultDiagnostic, relatedInfo); } - addErrorOrSuggestion(!isUncheckedJS, resultDiagnostic); + addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && @@ -72846,7 +73037,19 @@ var ts; // 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 // So the table *contains* `x` but `x` isn't actually in scope. // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. - return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + if (symbol) + return symbol; + var candidates; + if (symbols === globals) { + var primitives = ts.mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], function (s) { return symbols.has((s.charAt(0).toUpperCase() + s.slice(1))) + ? createSymbol(524288 /* TypeAlias */, s) + : undefined; }); + candidates = primitives.concat(ts.arrayFrom(symbols.values())); + } + else { + candidates = ts.arrayFrom(symbols.values()); + } + return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), candidates, meaning); }); return result; } @@ -75012,11 +75215,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } } return createPromiseReturnType(node, anyType); } + function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.parent = originalSymbol; + newSymbol.nameType = getStringLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + return createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + } + function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { + var hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier); + if (hasDefaultOnly && type && !isErrorType(type)) { + var synthType = type; + if (!synthType.defaultOnlyType) { + var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_4; + } + return synthType.defaultOnlyType; + } + return undefined; + } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { var _a; if (allowSyntheticDefaultImports && type && !isErrorType(type)) { @@ -75025,14 +75250,8 @@ var ts; var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false, moduleSpecifier); if (hasSyntheticDefault) { - var memberTable = ts.createSymbolTable(); - var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); - newSymbol.parent = originalSymbol; - newSymbol.nameType = getStringLiteralType("default"); - newSymbol.target = resolveSymbol(symbol); - memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); - var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); anonymousSymbol.type = defaultContainingObject; synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; } @@ -75740,12 +75959,12 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; + var type_5 = getBaseConstraintOfType(operandType) || operandType; // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_4.flags & 3 /* AnyOrUnknown */) { + if (type_5.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */; } - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -78335,7 +78554,9 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + if (!typeParameters) + return undefined; var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -78346,7 +78567,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); + checkIndexConstraints(type, type.symbol); checkTypeForDuplicateIndexSignatures(node); checkObjectTypeForDuplicateDeclarations(node); } @@ -78441,6 +78662,7 @@ var ts; checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { + checkGrammarMappedType(node); checkSourceElement(node.typeParameter); checkSourceElement(node.nameType); checkSourceElement(node.type); @@ -78457,6 +78679,12 @@ var ts; checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); } } + function checkGrammarMappedType(node) { + var _a; + if ((_a = node.members) === null || _a === void 0 ? void 0 : _a.length) { + return grammarErrorOnNode(node.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + } function checkThisType(node) { getTypeFromThisTypeNode(node); } @@ -78834,12 +79062,12 @@ var ts; case 264 /* ImportEqualsDeclaration */: case 267 /* NamespaceImport */: case 266 /* ImportClause */: - var result_12 = 0 /* None */; + var result_11 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { - result_12 |= getDeclarationSpaces(d); + result_11 |= getDeclarationSpaces(d); }); - return result_12; + return result_11; case 253 /* VariableDeclaration */: case 202 /* BindingElement */: case 255 /* FunctionDeclaration */: @@ -81402,7 +81630,7 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type, isStaticIndex) { + function checkIndexConstraints(type, symbol, isStaticIndex) { var indexInfos = getIndexInfosOfType(type); if (indexInfos.length === 0) { return; @@ -81413,15 +81641,15 @@ var ts; checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */, /*includeNonPublic*/ true), getNonMissingTypeOfSymbol(prop)); } } - var typeDeclaration = type.symbol.valueDeclaration; + var typeDeclaration = symbol.valueDeclaration; if (typeDeclaration && ts.isClassLike(typeDeclaration)) { for (var _b = 0, _c = typeDeclaration.members; _b < _c.length; _b++) { var member = _c[_b]; // Only process instance properties with computed names here. Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. if (!ts.isStatic(member) && !hasBindableName(member)) { - var symbol = getSymbolOfNode(member); - checkIndexConstraintForProperty(type, symbol, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol)); + var symbol_3 = getSymbolOfNode(member); + checkIndexConstraintForProperty(type, symbol_3, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol_3)); } } } @@ -81708,7 +81936,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); + checkMembersForOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -81737,14 +81965,13 @@ var ts; } } if (produceDiagnostics) { - checkIndexConstraints(type); - checkIndexConstraints(staticType, /*isStaticIndex*/ true); + checkIndexConstraints(type, symbol); + checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { - var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) { var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; @@ -81756,46 +81983,71 @@ var ts; if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { - checkClassMember(param, /*memberIsParameterProperty*/ true); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, + /* memberIsParameterProperty */ true); } }); } - checkClassMember(member); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, + /* memberIsParameterProperty */ false); }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; _loop_29(member); } - function checkClassMember(member, memberIsParameterProperty) { - var hasOverride = ts.hasOverrideModifier(member); - var hasStatic = ts.isStatic(member); - var isJs = ts.isInJSFile(member); - if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { - var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); - if (!declaredProp) { - return; - } - var thisType = hasStatic ? staticType : typeWithThis; - var baseType = hasStatic ? baseStaticType : baseWithThis; - var prop = getPropertyOfType(thisType, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); - var baseClassName = typeToString(baseWithThis); - if (prop && !baseProp && hasOverride) { - var suggestion = getSuggestedSymbolForNonexistentClassMember(ts.symbolName(declaredProp), baseType); + } + /** + * @param member Existing member node to be checked. + * Note: `member` cannot be a synthetic node. + */ + function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { + if (reportErrors === void 0) { reportErrors = true; } + var declaredProp = member.name + && getSymbolAtLocation(member.name) + || getSymbolAtLocation(member); + if (!declaredProp) { + return 0 /* Ok */; + } + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, ts.hasOverrideModifier(member), ts.hasAbstractModifier(member), ts.isStatic(member), memberIsParameterProperty, ts.symbolName(declaredProp), reportErrors ? member : undefined); + } + /** + * Checks a class member declaration for either a missing or an invalid `override` modifier. + * Note: this function can be used for speculative checking, + * i.e. checking a member that does not yet exist in the program. + * An example of that would be to call this function in a completions scenario, + * when offering a method declaration as completion. + * @param errorNode The node where we should report an error, or undefined if we should not report errors. + */ + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { + var isJs = ts.isInJSFile(node); + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { + var memberEscapedName = ts.escapeLeadingUnderscores(memberName); + var thisType = memberIsStatic ? staticType : typeWithThis; + var baseType = memberIsStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, memberEscapedName); + var baseProp = getPropertyOfType(baseType, memberEscapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && memberHasOverrideModifier) { + if (errorNode) { + var suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); // Again, using symbol name: note that's different from `symbol.escapedName` suggestion ? - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } - else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { - var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); - if (hasOverride) { - return; - } - if (!baseHasAbstract) { + return 2 /* HasInvalidOverride */; + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); + if (memberHasOverrideModifier) { + return 0 /* Ok */; + } + if (!baseHasAbstract) { + if (errorNode) { var diag = memberIsParameterProperty ? isJs ? ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : @@ -81803,20 +82055,28 @@ var ts; isJs ? ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; - error(member, diag, baseClassName); + error(errorNode, diag, baseClassName); } - else if (ts.hasAbstractModifier(member) && baseHasAbstract) { - error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + return 1 /* NeedsOverride */; + } + else if (memberHasAbstractModifier && baseHasAbstract) { + if (errorNode) { + error(errorNode, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); } + return 1 /* NeedsOverride */; } } - else if (hasOverride) { + } + else if (memberHasOverrideModifier) { + if (errorNode) { var className = typeToString(type); - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } + return 2 /* HasInvalidOverride */; } + return 0 /* Ok */; } 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 @@ -81859,6 +82119,31 @@ var ts; } } } + /** + * Checks a member declaration node to see if has a missing or invalid `override` modifier. + * @param node Class-like node where the member is declared. + * @param member Member declaration node. + * Note: `member` can be a synthetic node without a parent. + */ + function getMemberOverrideModifierStatus(node, member) { + if (!member.name) { + return 0 /* Ok */; + } + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var memberHasOverrideModifier = member.parent + ? ts.hasOverrideModifier(member) + : ts.hasSyntacticModifier(member, 16384 /* Override */); + var memberName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name)); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, ts.hasAbstractModifier(member), ts.isStatic(member), + /* memberIsParameterProperty */ false, memberName); + } function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -82129,7 +82414,7 @@ var ts; var baseType = _a[_i]; checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); } - checkIndexConstraints(type); + checkIndexConstraints(type, symbol); } } checkObjectTypeForDuplicateDeclarations(node); @@ -86320,6 +86605,9 @@ var ts; } } function checkGrammarProperty(node) { + if (ts.isComputedPropertyName(node.name) && ts.isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101 /* InKeyword */) { + return grammarErrorOnNode(node.parent.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } if (ts.isClassLike(node.parent)) { if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); @@ -86339,7 +86627,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 181 /* TypeLiteral */) { + else if (ts.isTypeLiteralNode(node.parent)) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -87016,7 +87304,7 @@ var ts; return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); case 194 /* MappedType */: ts.Debug.type(node); - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 195 /* LiteralType */: ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); @@ -94852,11 +95140,11 @@ var ts; currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } - function getJsxFactoryCalleePrimitive(childrenLength) { - return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx"; + function getJsxFactoryCalleePrimitive(isStaticChildren) { + return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx"; } - function getJsxFactoryCallee(childrenLength) { - var type = getJsxFactoryCalleePrimitive(childrenLength); + function getJsxFactoryCallee(isStaticChildren) { + var type = getJsxFactoryCalleePrimitive(isStaticChildren); return getImplicitImportForName(type); } function getImplicitJsxFragmentReference() { @@ -95003,60 +95291,37 @@ var ts; return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node); } function convertJsxChildrenToChildrenPropObject(children) { + var prop = convertJsxChildrenToChildrenPropAssignment(children); + return prop && factory.createObjectLiteralExpression([prop]); + } + function convertJsxChildrenToChildrenPropAssignment(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); - if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) - ]); + if (ts.length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) { + var result_12 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_12 && factory.createPropertyAssignment("children", result_12); } var result = ts.mapDefined(children, transformJsxChildToExpression); - return !result.length ? undefined : factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) - ]); + return ts.length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined; } function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; + var childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined; var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; }); var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties; - var segments = []; - if (attrs.length) { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - } - if (children && children.length) { - var result = convertJsxChildrenToChildrenPropObject(children); - if (result) { - segments.push(result); - } - } - if (segments.length === 0) { - objectProperties = factory.createObjectLiteralExpression([]); - // When there are no attributes, React wants {} - } - else { - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments); - } - return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location); + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : + factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : ts.emptyArray); // When there are no attributes, React wants {} + return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || ts.emptyArray, isChild, location); } - function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) { + function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { + var _a; + var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); + var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; if (compilerOptions.jsx === 5 /* ReactJSXDev */) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { // isStaticChildren development flag - args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse()); + args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); // __source development flag var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos); args.push(factory.createObjectLiteralExpression([ @@ -95068,7 +95333,7 @@ var ts; args.push(factory.createThis()); } } - var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location); + var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args), location); if (isChild) { ts.startOnNewLine(element); } @@ -95076,38 +95341,9 @@ var ts; } function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; var attrs = node.attributes.properties; - if (attrs.length === 0) { - objectProperties = factory.createNull(); - // When there are no attributes, React wants "null" - } - else { - var target = ts.getEmitScriptTarget(compilerOptions); - if (target && target >= 5 /* ES2018 */) { - objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { - return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); - }))); - } - else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); - } - } - } + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs) : + factory.createNull(); // When there are no attributes, React wants "null" var callee = currentFileState.importSpecifier === undefined ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 node) @@ -95127,7 +95363,7 @@ var ts; } } return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), - /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location); + /*keyAttr*/ undefined, children, isChild, location); } function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 @@ -95140,6 +95376,36 @@ var ts; function transformJsxSpreadAttributeToSpreadAssignment(node) { return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); } + function transformJsxAttributesToObjectProps(attrs, children) { + var target = ts.getEmitScriptTarget(compilerOptions); + return target && target >= 5 /* ES2018 */ ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : + transformJsxAttributesToExpression(attrs, children); + } + function transformJsxAttributesToProps(attrs, children) { + var props = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return ts.map(attrs, function (attr) { return isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr); }); + })); + if (children) { + props.push(children); + } + return props; + } + function transformJsxAttributesToExpression(attrs, children) { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var expressions = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + expressions.unshift(factory.createObjectLiteralExpression()); + } + if (children) { + expressions.push(factory.createObjectLiteralExpression([children])); + } + return ts.singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -98555,78 +98821,17 @@ var ts; * @param node A TemplateExpression node. */ function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - // createAdd will check if each expression binds less closely than binary '+'. - // If it does, it wraps the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var expression = ts.reduceLeft(expressions, factory.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - /** - * Gets a value indicating whether we need to include the head of a TemplateExpression. - * - * @param node A TemplateExpression node. - */ - function shouldAddTemplateHead(node) { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - /** - * Adds the head of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(factory.createStringLiteral(node.head.text)); - } - /** - * Visits and adds the template spans of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateSpans(expressions, node) { + var expression = factory.createStringLiteral(node.head.text); for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { var span = _a[_i]; - expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span.literal.text.length !== 0) { - expressions.push(factory.createStringLiteral(span.literal.text)); + var args = [ts.visitNode(span.expression, visitor, ts.isExpression)]; + if (span.literal.text.length > 0) { + args.push(factory.createStringLiteral(span.literal.text)); } + expression = factory.createCallExpression(factory.createPropertyAccessExpression(expression, "concat"), + /*typeArguments*/ undefined, args); } + return ts.setTextRange(expression, node); } /** * Visits the `super` keyword @@ -108246,7 +108451,14 @@ var ts; // clear the parenthesizer rule as we ascend currentParenthesizerRule = undefined; } - function pipelineEmitWithHintWorker(hint, node) { + function pipelineEmitWithHintWorker(hint, node, allowSnippets) { + if (allowSnippets === void 0) { allowSnippets = true; } + if (allowSnippets) { + var snippet = ts.getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -108855,6 +109067,28 @@ var ts; } } // + // Snippet Elements + // + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1 /* Placeholder */: + emitPlaceholder(hint, node, snippet); + break; + case 0 /* TabStop */: + emitTabStop(snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite("${" + snippet.order + ":"); // `${2:` + pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...` + nonEscapingWrite("}"); // `}` + // `${2:...}` + } + function emitTabStop(snippet) { + nonEscapingWrite("$" + snippet.order); + } + // // Identifiers // function emitIdentifier(node) { @@ -111093,6 +111327,15 @@ var ts; function writeProperty(s) { writer.writeProperty(s); } + function nonEscapingWrite(s) { + // This should be defined in a snippet-escaping text writer. + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } + else { + writer.write(s); + } + } function writeLine(count) { if (count === void 0) { count = 1; } for (var i = 0; i < count; i++) { @@ -112362,7 +112605,7 @@ var ts; var rootResult = tryReadDirectory(rootDir, rootDirPath); var rootSymLinkResult; if (rootResult !== undefined) { - return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -113334,7 +113577,7 @@ var ts; break; case ts.FileIncludeKind.TypeReferenceDirective: (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end); - packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), getModeForResolutionAtIndex(file, index))) === null || _g === void 0 ? void 0 : _g.packageId; + packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId; break; case ts.FileIncludeKind.LibReferenceDirective: (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end); @@ -113896,15 +114139,15 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_13 = []; var i = 0; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i)); i++; - result_14.push(resolvedModule); + result_13.push(resolvedModule); } - return result_14; + return result_13; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -114196,8 +114439,8 @@ var ts; var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); }); var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile); // ensure that types resolutions are still correct - var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); - if (typeReferenceEesolutionsChanged) { + var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); + if (typeReferenceResolutionsChanged) { structureIsReused = 1 /* SafeModules */; newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions); } @@ -115485,6 +115728,21 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { + var isNightly = ts.stringContains(ts.version, "-dev"); + if (!isNightly) { + if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); + } + else if (ts.getEmitModuleKind(options) === ts.ModuleKind.NodeNext) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext"); + } + } if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } @@ -115633,7 +115891,9 @@ var ts; } } if (options.resolveJsonModule) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } // Any emit other than common js, amd, es2015 or esnext is error @@ -115961,8 +116221,8 @@ var ts; function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + function createOptionValueDiagnostic(option1, message, arg0, arg1) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1); } function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); @@ -118206,6 +118466,9 @@ var ts; else { resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile); perDirectoryResolution.set(name, mode, resolution); + if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { + resolutionHost.onDiscoveredSymlink(); + } } resolutionsInFile.set(name, mode, resolution); watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); @@ -118674,6 +118937,11 @@ var ts; } } ts.createResolutionCache = createResolutionCache; + function resolutionIsSymlink(resolution) { + var _a, _b; + return !!(((_a = resolution.resolvedModule) === null || _a === void 0 ? void 0 : _a.originalPath) || + ((_b = resolution.resolvedTypeReferenceDirective) === null || _b === void 0 ? void 0 : _b.originalPath)); + } })(ts || (ts = {})); // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ @@ -118966,9 +119234,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_14 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_14) + return result_14; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -118988,10 +119256,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_15 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_15) + return result_15; } }); }); @@ -119284,13 +119552,15 @@ var ts; if (host.fileExists(packageJsonPath)) { var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); // TODO: Inject `require` or `import` condition based on the intended import mode - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; - if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; - return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); - } - if (packageJsonContent.exports) { - return { moduleFileToTry: path, blockedByExports: true }; + if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + if (fromExports) { + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); + } + if (packageJsonContent.exports) { + return { moduleFileToTry: path, blockedByExports: true }; + } } var versionPaths = packageJsonContent.typesVersions ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -120332,6 +120602,9 @@ var ts; sourceFilesCache.set(path, false); } } + if (sourceFile) { + sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); + } return sourceFile; } return hostSourceFile.sourceFile; @@ -121288,11 +121561,11 @@ var ts; (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [state.host.realpath ? toPath(state, state.host.realpath(path)) : path, data]; - })); if (state.watch) { + state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { + var path = _a[0], data = _a[1]; + return [state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data]; + })); state.builderPrograms.set(projectPath, program); } step++; @@ -124072,28 +124345,85 @@ var ts; /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { var current = sourceFile; - outer: while (true) { + var foundToken; + var _loop_1 = function () { // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { - var child = _a[_i]; - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + var children = current.getChildren(sourceFile); + var i = ts.binarySearchKey(children, position, function (_, i) { return i; }, function (middle, _) { + // This last callback is more of a selector than a comparator - + // `EqualTo` causes the `middle` result to be returned + // `GreaterThan` causes recursion on the left of the middle + // `LessThan` causes recursion on the right of the middle + // Let's say you have 3 nodes, spanning positons + // pos: 1, end: 3 + // pos: 3, end: 3 + // pos: 3, end: 5 + // and you're looking for the token at positon 3 - all 3 of these nodes are overlapping with position 3. + // In fact, there's a _good argument_ that node 2 shouldn't even be allowed to exist - depending on if + // the start or end of the ranges are considered inclusive, it's either wholly subsumed by the first or the last node. + // Unfortunately, such nodes do exist. :( - See fourslash/completionsImport_tsx.tsx - empty jsx attributes create + // a zero-length node. + // What also you may not expect is that which node we return depends on the includePrecedingTokenAtEndPosition flag. + // Specifically, if includePrecedingTokenAtEndPosition is set, we return the 1-3 node, while if it's unset, we + // return the 3-5 node. (The zero length node is never correct.) This is because the includePrecedingTokenAtEndPosition + // flag causes us to return the first node whose end position matches the position and which produces and acceptable token + // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the + // position and whose end is greater than the position. + var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { - // If this child begins after position, then all subsequent children will as well. - break; - } - var end = child.getEnd(); - if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { - current = child; - continue outer; + return 1 /* GreaterThan */; } - else if (includePrecedingTokenAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { - return previousToken; + // first element whose start position is before the input and whose end position is after or equal to the input + if (nodeContainsPosition(children[middle])) { + if (children[middle - 1]) { + // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position + if (nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } } + return 0 /* EqualTo */; } + // this complex condition makes us left-recur around a zero-length node when includePrecedingTokenAtEndPosition is set, rather than right-recur on it + if (includePrecedingTokenAtEndPosition && start === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } + return -1 /* LessThan */; + }); + if (foundToken) { + return { value: foundToken }; } - return current; + if (i >= 0 && children[i]) { + current = children[i]; + return "continue-outer"; + } + return { value: current }; + }; + outer: while (true) { + var state_1 = _loop_1(); + if (typeof state_1 === "object") + return state_1.value; + switch (state_1) { + case "continue-outer": continue outer; + } + } + function nodeContainsPosition(node) { + var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + return false; + } + var end = node.getEnd(); + if (position < end || (position === end && (node.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + return true; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, node); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + foundToken = previousToken; + return true; + } + } + return false; } } /** @@ -124736,14 +125066,14 @@ var ts; return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); } ts.programContainsModules = programContainsModules; - function programContainsEs6Modules(program) { + function programContainsEsModules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } - ts.programContainsEs6Modules = programContainsEs6Modules; - function compilerOptionsIndicateEs6Modules(compilerOptions) { + ts.programContainsEsModules = programContainsEsModules; + function compilerOptionsIndicateEsModules(compilerOptions) { return !!compilerOptions.module || ts.getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ || !!compilerOptions.noEmit; } - ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + ts.compilerOptionsIndicateEsModules = compilerOptionsIndicateEsModules; function createModuleSpecifierResolutionHost(program, host) { // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. @@ -125130,9 +125460,9 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.linkText); } ts.linkTextPart = linkTextPart; - function linkNamePart(name, target) { + function linkNamePart(text, target) { return { - text: ts.getTextOfNode(name), + text: text, kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], target: { fileName: ts.getSourceFileOfNode(target).fileName, @@ -125157,20 +125487,41 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var suffix = findLinkNameEnd(link.text); + var name = ts.getTextOfNode(link.name) + link.text.slice(0, suffix); + var text = link.text.slice(suffix); var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); if (decl) { - parts.push(linkNamePart(link.name, decl)); - if (link.text) - parts.push(linkTextPart(link.text)); + parts.push(linkNamePart(name, decl)); + if (text) + parts.push(linkTextPart(text)); } else { - parts.push(linkTextPart(ts.getTextOfNode(link.name) + " " + link.text)); + parts.push(linkTextPart(name + (suffix ? "" : " ") + text)); } } parts.push(linkPart("}")); return parts; } ts.buildLinkParts = buildLinkParts; + function findLinkNameEnd(text) { + if (text.indexOf("()") === 0) + return 2; + if (text[0] !== "<") + return 0; + var brackets = 0; + var i = 0; + while (i < text.length) { + if (text[i] === "<") + brackets++; + if (text[i] === ">") + brackets--; + i++; + if (!brackets) + return i; + } + return 0; + } var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -126035,6 +126386,16 @@ var ts; return decisionFromFile !== null && decisionFromFile !== void 0 ? decisionFromFile : program.usesUriStyleNodeCoreModules; } ts.shouldUseUriStyleNodeCoreModules = shouldUseUriStyleNodeCoreModules; + function getNewLineKind(newLineCharacter) { + return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + } + ts.getNewLineKind = getNewLineKind; + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + ts.diagnosticToString = diagnosticToString; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -126074,19 +126435,24 @@ var ts; } var isDefault = exportKind === 1 /* Default */; var namedSymbol = isDefault && ts.getLocalSymbolForExportDefault(symbol) || symbol; - // A re-export merged with an export from a module augmentation can result in `symbol` - // being an external module symbol; the name it is re-exported by will be `symbolTableKey` - // (which comes from the keys of `moduleSymbol.exports`.) - var importedName = ts.isExternalModuleSymbol(namedSymbol) + // 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`. + // 2. A re-export merged with an export from a module augmentation can result in `symbol` + // being an external module symbol; the name it is re-exported by will be `symbolTableKey` + // (which comes from the keys of `moduleSymbol.exports`.) + // 3. Otherwise, we have a default/namespace import that can be imported by any name, and + // `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to + // get a better name. + var importedName = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) ? ts.unescapeLeadingUnderscores(symbolTableKey) : ts.getNameForExportedSymbol(namedSymbol, scriptTarget); var moduleName = ts.stripQuotes(moduleSymbol.name); var id = exportInfoId++; + var target = ts.skipAlias(symbol, checker); var storedSymbol = symbol.flags & 33554432 /* Transient */ ? undefined : symbol; var storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? undefined : moduleSymbol; if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); - exportInfo.add(key(importedName, symbol, moduleName, checker), { + exportInfo.add(key(importedName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { id: id, symbolTableKey: symbolTableKey, symbolName: importedName, @@ -126094,16 +126460,16 @@ var ts; moduleFile: moduleFile, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: exportKind, - targetFlags: ts.skipAlias(symbol, checker).flags, + targetFlags: target.flags, isFromPackageJson: isFromPackageJson, symbol: storedSymbol, moduleSymbol: storedModuleSymbol, }); }, - get: function (importingFile, importedName, symbol, moduleName, checker) { + get: function (importingFile, key) { if (importingFile !== usableByFileName) return; - var result = exportInfo.get(key(importedName, symbol, moduleName, checker)); + var result = exportInfo.get(key); return result === null || result === void 0 ? void 0 : result.map(rehydrateCachedInfo); }, forEach: function (importingFile, action) { @@ -126111,7 +126477,7 @@ var ts; return; exportInfo.forEach(function (info, key) { var _a = parseKey(key), symbolName = _a.symbolName, ambientModuleName = _a.ambientModuleName; - action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName); + action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName, key); }); }, releaseSymbols: function () { @@ -126176,26 +126542,16 @@ var ts; isFromPackageJson: isFromPackageJson, }; } - function key(importedName, symbol, moduleName, checker) { - var unquoted = ts.stripQuotes(moduleName); - var moduleKey = ts.isExternalModuleNameRelative(unquoted) ? "/" : unquoted; - var target = ts.skipAlias(symbol, checker); - return importedName + "|" + createSymbolKey(target) + "|" + moduleKey; + function key(importedName, symbol, ambientModuleName, checker) { + var moduleKey = ambientModuleName || ""; + return importedName + "|" + ts.getSymbolId(ts.skipAlias(symbol, checker)) + "|" + moduleKey; } function parseKey(key) { var symbolName = key.substring(0, key.indexOf("|")); var moduleKey = key.substring(key.lastIndexOf("|") + 1); - var ambientModuleName = moduleKey === "/" ? undefined : moduleKey; + var ambientModuleName = moduleKey === "" ? undefined : moduleKey; return { symbolName: symbolName, ambientModuleName: ambientModuleName }; } - function createSymbolKey(symbol) { - var key = symbol.name; - while (symbol.parent) { - key += "," + symbol.parent.name; - symbol = symbol.parent; - } - return key; - } function fileIsGlobalOnly(file) { return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; } @@ -126205,7 +126561,7 @@ var ts; } var oldFileStatementIndex = -1; var newFileStatementIndex = -1; - var _loop_1 = function (ambientModuleName) { + var _loop_2 = function (ambientModuleName) { var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); @@ -126215,9 +126571,9 @@ var ts; }; for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { var ambientModuleName = _a[_i]; - var state_1 = _loop_1(ambientModuleName); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_2(ambientModuleName); + if (typeof state_2 === "object") + return state_2.value; } return true; } @@ -126317,7 +126673,7 @@ var ts; cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, scriptTarget, checker); } checker.forEachExportAndPropertyOfModule(moduleSymbol, function (exported, key) { - if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, exported)) { + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, key)) { cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, scriptTarget, checker); } }); @@ -127637,7 +127993,7 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { - function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); return entries && convertPathCompletions(entries); @@ -127645,12 +128001,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -127660,7 +128016,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -128059,7 +128415,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_2 = function (name, kind, extension) { + var _loop_3 = function (name, kind, extension) { // 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 === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -128067,7 +128423,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_2(name, kind, extension); + _loop_3(name, kind, extension); } } } @@ -128102,7 +128458,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_3 = function (moduleName) { + var _loop_4 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -128110,7 +128466,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_3(moduleName); + _loop_4(moduleName); } } if (!foundGlobal) { @@ -128386,6 +128742,8 @@ var ts; (function (CompletionSource) { /** Completions that require `this.` insertion text */ CompletionSource["ThisProperty"] = "ThisProperty/"; + /** Auto-import that comes attached to a class member snippet */ + CompletionSource["ClassMemberSnippet"] = "ClassMemberSnippet/"; })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { @@ -128494,7 +128852,6 @@ var ts; } // If the request is a continuation of an earlier `isIncomplete` response, // we can continue it from the cached previous response. - var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a = host.getIncompleteCompletionsCache) === null || _a === void 0 ? void 0 : _a.call(host) : undefined; if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && ts.isIdentifier(previousToken)) { @@ -128506,7 +128863,7 @@ var ts; else { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.clear(); } - var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, typeChecker, compilerOptions, host, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences); if (stringCompletions) { return stringCompletions; } @@ -128520,7 +128877,7 @@ var ts; } switch (completionData.kind) { case 0 /* Data */: - var response = completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); + var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences); if (response === null || response === void 0 ? void 0 : response.isIncomplete) { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.set(response); } @@ -128540,20 +128897,19 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function completionEntryDataIsResolved(data) { + return !!(data === null || data === void 0 ? void 0 : data.moduleSpecifier); + } function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken) { - var _a; var previousResponse = cache.get(); if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var checker = program.getTypeChecker(); - var autoImportProvider = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); - var autoImportProviderChecker = autoImportProvider === null || autoImportProvider === void 0 ? void 0 : autoImportProvider.getTypeChecker(); var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, preferences, /*isForImportStatementCompletion*/ false, function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { - if (!entry.hasAction || !entry.source || !entry.data || entry.data.moduleSpecifier) { + if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) { // Not an auto import or already resolved; keep as is return entry; } @@ -128561,8 +128917,8 @@ var ts; // No longer matches typed characters; filter out return undefined; } - var _a = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)), symbol = _a.symbol, origin = _a.origin; - var info = exportMap.get(file.path, entry.name, symbol, origin.moduleSymbol.name, origin.isFromPackageJson ? autoImportProviderChecker : checker); + var origin = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)).origin; + var info = exportMap.get(file.path, entry.data.exportMapKey); var result = info && context.tryResolve(info, !ts.isExternalModuleNameRelative(ts.stripQuotes(origin.moduleSymbol.name))); if (!result) return entry; @@ -128618,7 +128974,7 @@ var ts; // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 79 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; // Verify if the file is JSX language variant if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { @@ -128630,7 +128986,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); // TODO: GH#18217 } else { @@ -128638,7 +128994,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -128744,14 +129100,16 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { - var _a; + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind) { + var _a, _b; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(replacementToken); var data; var isSnippet; + var source = getSourceFromOrigin(origin); var sourceDisplay; var hasAction; + var typeChecker = program.getTypeChecker(); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -128802,12 +129160,16 @@ var ts; isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; } } - if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { - return undefined; - } - if (originIsExport(origin) || originIsResolvedExport(origin)) { - data = originToCompletionEntryData(origin); - hasAction = !importCompletionNode; + if (preferences.includeCompletionsWithClassMemberSnippets && + preferences.includeCompletionsWithInsertText && + completionKind === 3 /* MemberLike */ && + isClassLikeMemberCompletion(symbol, location)) { + var importAdder = void 0; + (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); + if (importAdder === null || importAdder === void 0 ? void 0 : importAdder.hasFixes()) { + hasAction = true; + source = CompletionSource.ClassMemberSnippet; + } } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location); if (kind === "JSX attribute" /* jsxAttribute */ && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { @@ -128819,7 +129181,7 @@ var ts; && !(type.flags & 1048576 /* Union */ && ts.find(type.types, function (type) { return !!(type.flags & 528 /* BooleanLike */); }))) { if (type.flags & 402653316 /* StringLike */ || (type.flags & 1048576 /* Union */ && ts.every(type.types, function (type) { return !!(type.flags & (402653316 /* StringLike */ | 32768 /* Undefined */)); }))) { // If is string like or undefined use quotes - insertText = escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); + insertText = ts.escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); isSnippet = true; } else { @@ -128828,12 +129190,16 @@ var ts; } } if (useBraces_1) { - insertText = escapeSnippetText(name) + "={$1}"; + insertText = ts.escapeSnippetText(name) + "={$1}"; isSnippet = true; } - if (isSnippet) { - replacementSpan = ts.createTextSpanFromNode(location, sourceFile); - } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = originToCompletionEntryData(origin); + hasAction = !importCompletionNode; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but @@ -128847,7 +129213,7 @@ var ts; kind: kind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), sortText: sortText, - source: getSourceFromOrigin(origin), + source: source, hasAction: hasAction ? true : undefined, isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, @@ -128859,17 +129225,222 @@ var ts; data: data, }; } - function escapeSnippetText(text) { - return text.replace(/\$/gm, "\\$"); + function isClassLikeMemberCompletion(symbol, location) { + // TODO: support JS files. + if (ts.isInJSFile(location)) { + return false; + } + // Completion symbol must be for a class member. + var memberFlags = 106500 /* ClassMember */ + & 900095 /* EnumMemberExcludes */; + /* In + `class C { + | + }` + `location` is a class-like declaration. + In + `class C { + m| + }` + `location` is an identifier, + `location.parent` is a class element declaration, + and `location.parent.parent` is a class-like declaration. + In + `abstract class C { + abstract + abstract m| + }` + `location` is a syntax list (with modifiers as children), + and `location.parent` is a class-like declaration. + */ + return !!(symbol.flags & memberFlags) && + (ts.isClassLike(location) || + (location.parent && + location.parent.parent && + ts.isClassElement(location.parent) && + location === location.parent.name && + ts.isClassLike(location.parent.parent)) || + (location.parent && + ts.isSyntaxList(location) && + ts.isClassLike(location.parent))); + } + function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken) { + var classLikeDeclaration = ts.findAncestor(location, ts.isClassLike); + if (!classLikeDeclaration) { + return { insertText: name }; + } + var isSnippet; + var insertText = name; + var checker = program.getTypeChecker(); + var sourceFile = location.getSourceFile(); + var printer = createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target, + omitTrailingSemicolon: false, + newLine: ts.getNewLineKind(ts.getNewLineCharacter(options, ts.maybeBind(host, host.getNewLine))), + }); + var importAdder = ts.codefix.createImportAdder(sourceFile, program, preferences, host); + var body; + if (preferences.includeCompletionsWithSnippetText) { + isSnippet = true; + // We are adding a tabstop (i.e. `$0`) in the body of the suggested member, + // if it has one, so that the cursor ends up in the body once the completion is inserted. + // Note: this assumes we won't have more than one body in the completion nodes, which should be the case. + var emptyStatement = ts.factory.createExpressionStatement(ts.factory.createIdentifier("")); + ts.setSnippetElement(emptyStatement, { kind: 0 /* TabStop */, order: 0 }); + body = ts.factory.createBlock([emptyStatement], /* multiline */ true); + } + else { + body = ts.factory.createBlock([], /* multiline */ true); + } + var modifiers = 0 /* None */; + // Whether the suggested member should be abstract. + // e.g. in `abstract class C { abstract | }`, we should offer abstract method signatures at position `|`. + // Note: We are relying on checking if the context token is `abstract`, + // since other visibility modifiers (e.g. `protected`) should come *before* `abstract`. + // However, that is not true for the e.g. `override` modifier, so this check has its limitations. + var isAbstract = contextToken && isModifierLike(contextToken) === 126 /* AbstractKeyword */; + var completionNodes = []; + ts.codefix.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { program: program, host: host }, preferences, importAdder, + // `addNewNodeForMemberSymbol` calls this callback function for each new member node + // it adds for the given member symbol. + // We store these member nodes in the `completionNodes` array. + // Note: there might be: + // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; + // - One node; + // - More than one node if the member is overloaded (e.g. a method with overload signatures). + function (node) { + var requiredModifiers = 0 /* None */; + if (isAbstract) { + requiredModifiers |= 128 /* Abstract */; + } + if (ts.isClassElement(node) + && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node) === 1 /* NeedsOverride */) { + requiredModifiers |= 16384 /* Override */; + } + var presentModifiers = 0 /* None */; + if (!completionNodes.length) { + // Omit already present modifiers from the first completion node/signature. + if (contextToken) { + presentModifiers = getPresentModifiers(contextToken); + } + // Keep track of added missing required modifiers and modifiers already present. + // This is needed when we have overloaded signatures, + // so this callback will be called for multiple nodes/signatures, + // and we need to make sure the modifiers are uniform for all nodes/signatures. + modifiers = node.modifierFlagsCache | requiredModifiers | presentModifiers; + } + node = ts.factory.updateModifiers(node, modifiers & (~presentModifiers)); + completionNodes.push(node); + }, body, 2 /* Property */, isAbstract); + if (completionNodes.length) { + insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + } + return { insertText: insertText, isSnippet: isSnippet, importAdder: importAdder }; + } + function getPresentModifiers(contextToken) { + var modifiers = 0 /* None */; + var contextMod; + /* + Cases supported: + In + `class C { + public abstract | + }` + `contextToken` is ``abstract`` (as an identifier), + `contextToken.parent` is property declaration, + `location` is class declaration ``class C { ... }``. + In + `class C { + protected override m| + }` + `contextToken` is ``override`` (as a keyword), + `contextToken.parent` is property declaration, + `location` is identifier ``m``, + `location.parent` is property declaration ``protected override m``, + `location.parent.parent` is class declaration ``class C { ... }``. + */ + if (contextMod = isModifierLike(contextToken)) { + modifiers |= ts.modifierToFlag(contextMod); + } + if (ts.isPropertyDeclaration(contextToken.parent)) { + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + } + return modifiers; } - function originToCompletionEntryData(origin) { + function isModifierLike(node) { + if (ts.isModifier(node)) { + return node.kind; + } + if (ts.isIdentifier(node) && node.originalKeywordKind && ts.isModifierKind(node.originalKeywordKind)) { + return node.originalKeywordKind; + } + return undefined; + } + function createSnippetPrinter(printerOptions) { + var printer = ts.createPrinter(printerOptions); + var baseWriter = ts.createTextWriter(ts.getNewLineCharacter(printerOptions)); + var writer = __assign(__assign({}, baseWriter), { write: function (s) { return baseWriter.write(ts.escapeSnippetText(s)); }, nonEscapingWrite: baseWriter.write, writeLiteral: function (s) { return baseWriter.writeLiteral(ts.escapeSnippetText(s)); }, writeStringLiteral: function (s) { return baseWriter.writeStringLiteral(ts.escapeSnippetText(s)); }, writeSymbol: function (s, symbol) { return baseWriter.writeSymbol(ts.escapeSnippetText(s), symbol); }, writeParameter: function (s) { return baseWriter.writeParameter(ts.escapeSnippetText(s)); }, writeComment: function (s) { return baseWriter.writeComment(ts.escapeSnippetText(s)); }, writeProperty: function (s) { return baseWriter.writeProperty(ts.escapeSnippetText(s)); } }); return { + printSnippetList: printSnippetList, + }; + /* Snippet-escaping version of `printer.printList`. */ + function printSnippetList(format, list, sourceFile) { + writer.clear(); + printer.writeList(format, list, sourceFile, writer); + return writer.getText(); + } + } + function originToCompletionEntryData(origin) { + var ambientModuleName = origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name); + var isPackageJsonImport = origin.isFromPackageJson ? true : undefined; + if (originIsResolvedExport(origin)) { + var resolvedData = { + exportName: origin.exportName, + moduleSpecifier: origin.moduleSpecifier, + ambientModuleName: ambientModuleName, + fileName: origin.fileName, + isPackageJsonImport: isPackageJsonImport, + }; + return resolvedData; + } + var unresolvedData = { exportName: origin.exportName, + exportMapKey: origin.exportMapKey, fileName: origin.fileName, ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), isPackageJsonImport: origin.isFromPackageJson ? true : undefined, - moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, }; + return unresolvedData; + } + function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) { + var isDefaultExport = data.exportName === "default" /* Default */; + var isFromPackageJson = !!data.isPackageJsonImport; + if (completionEntryDataIsResolved(data)) { + var resolvedOrigin = { + kind: 32 /* ResolvedExport */, + exportName: data.exportName, + moduleSpecifier: data.moduleSpecifier, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return resolvedOrigin; + } + var unresolvedOrigin = { + kind: 4 /* Export */, + exportName: data.exportName, + exportMapKey: data.exportMapKey, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return unresolvedOrigin; } function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, contextToken, origin, useSemicolons, options, preferences) { var _a, _b, _c; @@ -128887,10 +129458,10 @@ var ts; var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? ts.tokenToString(151 /* TypeKeyword */) + " " : ""; var suffix = useSemicolons ? ";" : ""; switch (importKind) { - case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; - case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; - case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; - case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + ts.escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; } } function quotePropertyName(sourceFile, preferences, name) { @@ -128914,11 +129485,12 @@ var ts; return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { var _a; var start = ts.timestamp(); var variableDeclaration = getVariableDeclaration(location); var useSemicolons = ts.probablyUsesSemicolons(sourceFile); + var typeChecker = program.getTypeChecker(); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. @@ -128934,7 +129506,7 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var sortTextId = (_a = symbolToSortTextIdMap === null || symbolToSortTextIdMap === void 0 ? void 0 : symbolToSortTextIdMap[ts.getSymbolId(symbol)]) !== null && _a !== void 0 ? _a : 11 /* LocationPriority */; var sortText = (isDeprecated(symbol, typeChecker) ? 8 /* DeprecatedOffset */ + sortTextId : sortTextId).toString(); - var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); + var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind); if (!entry) { continue; } @@ -129027,11 +129599,13 @@ var ts; if (entryId.data) { var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); if (autoImport) { + var _a = getRelevantTokens(position, sourceFile), contextToken_1 = _a.contextToken, previousToken_1 = _a.previousToken; return { type: "symbol", symbol: autoImport.symbol, location: ts.getTouchingPropertyName(sourceFile, position), - previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + previousToken: previousToken_1, + contextToken: contextToken_1, isJsxInitializer: false, isTypeOnlyLocation: false, origin: autoImport.origin, @@ -129046,7 +129620,7 @@ var ts; if (completionData.kind !== 0 /* Data */) { return { type: "request", request: completionData }; } - var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, contextToken = completionData.contextToken, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; var literal = ts.find(literals, function (l) { return completionNameForLiteral(sourceFile, preferences, l) === entryId.name; }); if (literal !== undefined) return { type: "literal", literal: literal }; @@ -129057,15 +129631,15 @@ var ts; return ts.firstDefined(symbols, function (symbol, index) { var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); - return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + return info && info.name === entryId.name && (entryId.source === CompletionSource.ClassMemberSnippet && symbol.flags & 106500 /* ClassMember */ || getSourceFromOrigin(origin) === entryId.source) + ? { type: "symbol", symbol: symbol, location: location, origin: origin, contextToken: contextToken, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - var name = entryId.name; + var name = entryId.name, source = entryId.source, data = entryId.data; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); @@ -129089,8 +129663,8 @@ var ts; } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, contextToken_2 = symbolCompletion.contextToken, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken_2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -129119,21 +129693,34 @@ var ts; return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source) { if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { - var _a = getRelevantTokens(position, sourceFile), contextToken = _a.contextToken, previousToken_1 = _a.previousToken; - if (previousToken_1 && getImportStatementCompletionInfo(contextToken || previousToken_1).replacementNode) { + var _a = getRelevantTokens(position, sourceFile), contextToken_3 = _a.contextToken, previousToken_2 = _a.previousToken; + if (previousToken_2 && getImportStatementCompletionInfo(contextToken_3 || previousToken_2).replacementNode) { // Import statement completion: 'import c|' return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; } } + if (source === CompletionSource.ClassMemberSnippet) { + var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken).importAdder; + if (importAdder) { + var changes = ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, importAdder.writeFixes); + return { + sourceDisplay: undefined, + codeActions: [{ + changes: changes, + description: ts.diagnosticToString([ts.Diagnostics.Includes_imports_of_types_referenced_by_0, name]), + }], + }; + } + } if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { return { codeActions: undefined, sourceDisplay: undefined }; } var checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); var moduleSymbol = origin.moduleSymbol; - var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _b = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; + var targetSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _b = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; ts.Debug.assert(!(data === null || data === void 0 ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -129645,6 +130232,7 @@ var ts; } } function addPropertySymbol(symbol, insertAwait, insertQuestionDot) { + var _a; // For a computed property with an accessible name like `Symbol.iterator`, // we'll add a completion for the *name* `Symbol` instead of for the property. // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. @@ -129658,19 +130246,33 @@ var ts; var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + if (!moduleSymbol || + !ts.isExternalModuleSymbol(moduleSymbol) || + typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) { symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; } else { - var origin = { - kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), - moduleSymbol: moduleSymbol, - isDefaultExport: false, - symbolName: firstAccessibleSymbol.name, - exportName: firstAccessibleSymbol.name, - fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, - }; - symbolToOriginInfoMap[index] = origin; + var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; + var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + exportKind: 0 /* Named */, + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol: moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, + }], sourceFile, program, host, preferences) || {}).moduleSpecifier; + if (moduleSpecifier) { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: fileName, + moduleSpecifier: moduleSpecifier, + }; + symbolToOriginInfoMap[index] = origin; + } } } else if (preferences.includeCompletionsWithInsertText) { @@ -129827,11 +130429,11 @@ var ts; // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; - // If already using ES6 modules, OK to continue using them. + // If already using ES modules, OK to continue using them. if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + if (ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. return ts.programContainsModules(program); @@ -129906,7 +130508,7 @@ var ts; var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, preferences, !!importCompletionNode, function (context) { - exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule) { + exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule, exportMapKey) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) return; if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) @@ -129931,6 +130533,7 @@ var ts; kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, moduleSpecifier: moduleSpecifier, symbolName: symbolName, + exportMapKey: exportMapKey, exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, fileName: exportInfo_1.moduleFileName, isDefaultExport: isDefaultExport, @@ -130012,8 +130615,9 @@ var ts; function isNewIdentifierDefinitionLocation() { if (contextToken) { var containingNodeKind = contextToken.parent.kind; + var tokenKind = keywordForNode(contextToken); // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(contextToken)) { + switch (tokenKind) { case 27 /* CommaToken */: return containingNodeKind === 207 /* CallExpression */ // func( a, | || containingNodeKind === 170 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ @@ -130048,10 +130652,14 @@ var ts; return containingNodeKind === 222 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: return containingNodeKind === 232 /* TemplateSpan */; // `aa ${10} dd ${| - case 123 /* PublicKeyword */: - case 121 /* PrivateKeyword */: - case 122 /* ProtectedKeyword */: - return containingNodeKind === 166 /* PropertyDeclaration */; // class A{ public | + case 131 /* AsyncKeyword */: + return containingNodeKind === 168 /* MethodDeclaration */ // const obj = { async c|() + || containingNodeKind === 295 /* ShorthandPropertyAssignment */; // const obj = { async c| + case 41 /* AsteriskToken */: + return containingNodeKind === 168 /* MethodDeclaration */; // const obj = { * c| + } + if (isClassMemberCompletionKeyword(tokenKind)) { + return true; } } return false; @@ -130754,18 +131362,7 @@ var ts; return undefined; var isDefaultExport = data.exportName === "default" /* Default */; symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; - return { - symbol: symbol, - origin: { - kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, - moduleSymbol: moduleSymbol, - symbolName: name, - isDefaultExport: isDefaultExport, - exportName: data.exportName, - fileName: data.fileName, - isFromPackageJson: !!data.isPackageJsonImport, - } - }; + return { symbol: symbol, origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) }; } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; @@ -133146,7 +133743,7 @@ var ts; result = references; continue; } - var _loop_4 = function (entry) { + var _loop_5 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -133178,7 +133775,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_4(entry); + _loop_5(entry); } } return result; @@ -135156,7 +135753,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -135188,7 +135785,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } } function combineNormal(pathA, pathB) { @@ -136125,7 +136722,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_7 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -136137,7 +136734,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_6(sourceFile); + _loop_7(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -138141,15 +138738,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_7 = function (start) { + var _loop_8 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_2 = _loop_7(start); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(start); + if (typeof state_3 === "object") + return state_3.value; } return -1; } @@ -138812,6 +139409,7 @@ var ts; return false; } } + Rename.nodeIsEligibleForRename = nodeIsEligibleForRename; })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); /* @internal */ @@ -139527,7 +140125,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_8 = function (n) { + var _loop_9 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -139537,9 +140135,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_3 = _loop_8(n); - if (typeof state_3 === "object") - return state_3.value; + var state_4 = _loop_9(n); + if (typeof state_4 === "object") + return state_4.value; } return undefined; } @@ -140131,10 +140729,12 @@ var ts; program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; var checker = program.getTypeChecker(); - if (sourceFile.commonJsModuleIndicator && - (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + var isCommonJSFile = sourceFile.impliedNodeFormat === ts.ModuleKind.CommonJS || ts.fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]); + if (!isCommonJSFile && + sourceFile.commonJsModuleIndicator && + (ts.programContainsEsModules(program) || ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { - diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); visitedNestedConvertibleFunctions.clear(); @@ -140183,7 +140783,7 @@ var ts; } } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; - // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + // convertToEsModule only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { @@ -141110,7 +141710,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -141129,7 +141729,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -144797,7 +145397,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_10 = function (sourceFile, node) { + var _loop_11 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -144810,7 +145410,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_10(sourceFile, node); + _loop_11(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -144869,14 +145469,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_11 = function (i) { + var _loop_12 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_11(i); + _loop_12(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -144954,7 +145554,7 @@ var ts; /** Note: output node may be mutated input node. */ function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = createWriter(newLineCharacter); - var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + var newLine = ts.getNewLineKind(newLineCharacter); ts.createPrinter({ newLine: newLine, neverAsciiEscape: true, @@ -145419,21 +146019,16 @@ var ts; (function (codefix) { var errorCodeToFixes = ts.createMultiMap(); var fixIdToRegistration = new ts.Map(); - function diagnosticToString(diag) { - return ts.isArray(diag) - ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) - : ts.getLocaleSpecificMessage(diag); - } function createCodeFixActionWithoutFixAll(fixName, changes, description) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, fixAllDescription && ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { @@ -145780,7 +146375,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_12 = function (identifier) { + var _loop_13 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -145813,7 +146408,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_12(identifier); + _loop_13(identifier); } return initializers && { initializers: initializers, @@ -146104,9 +146699,6 @@ var ts; }); function makeChange(changeTracker, sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (!ts.isIdentifier(token)) { - return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.Debug.formatSyntaxKind(token.kind)); - } var param = token.parent; if (!ts.isParameter(param)) { return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.Debug.formatSyntaxKind(token.kind)); @@ -146114,9 +146706,10 @@ var ts; var i = param.parent.parameters.indexOf(param); ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.factory.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); - changeTracker.replaceNode(sourceFile, token, replacement); + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -146696,7 +147289,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 131 /* AsyncKeyword */, options); - var _loop_13 = function (returnStatement) { + var _loop_14 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -146718,9 +147311,9 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_4 = _loop_13(returnStatement); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_14(returnStatement); + if (typeof state_5 === "object") + return state_5.value; } } function getReturnStatementsWithPromiseHandlers(body, checker) { @@ -147377,11 +147970,11 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code], getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); + var moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; @@ -147390,7 +147983,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEsModule", changes, ts.Diagnostics.Convert_to_ES_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -147414,7 +148007,7 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: new ts.Set() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); @@ -147547,7 +148140,7 @@ var ts; // `const a = require("b").c` --> `import { c as a } from "./b"; return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid syntax form " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid syntax form " + name.kind); } } function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { @@ -147732,7 +148325,7 @@ var ts; case 79 /* Identifier */: return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid name kind " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid name kind " + name.kind); } } /** @@ -148052,7 +148645,11 @@ var ts; } function doChange(changes, sourceFile, _a) { var container = _a.container, typeNode = _a.typeNode, constraint = _a.constraint, name = _a.name; - changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode(/*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), /*nameType*/ undefined, /*questionToken*/ undefined, typeNode)); + changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode( + /*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), + /*nameType*/ undefined, + /*questionToken*/ undefined, typeNode, + /*members*/ undefined)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -148190,7 +148787,7 @@ var ts; var addToExisting = new ts.Map(); /** Use `getNewImportEntry` for access */ var newImports = new ts.Map(); - return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; + return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes, hasFixes: hasFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start, useAutoImportProvider); if (!info || !info.fixes.length) @@ -148341,6 +148938,9 @@ var ts; ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); } } + function hasFixes() { + return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; + } } // Sorted with the preferred fix coming first. var ImportFixKind; @@ -148360,11 +148960,11 @@ var ts; AddAsTypeOnly[AddAsTypeOnly["Required"] = 2] = "Required"; AddAsTypeOnly[AddAsTypeOnly["NotAllowed"] = 4] = "NotAllowed"; })(AddAsTypeOnly || (AddAsTypeOnly = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] - : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); + ? [getSymbolExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] + : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); var fix = ts.Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); @@ -148402,7 +149002,7 @@ var ts; } } } - function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { + function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { @@ -148415,12 +149015,12 @@ var ts; return; } var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: defaultInfo.exportKind, targetFlags: ts.skipAlias(defaultInfo.symbol, checker).flags, isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (exported.name === symbolName && checker.getMergedSymbol(ts.skipAlias(exported, checker)) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: exported, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: 0 /* Named */, targetFlags: ts.skipAlias(exported, checker).flags, isFromPackageJson: isFromPackageJson }); } } @@ -148671,12 +149271,14 @@ var ts; } var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; return fixes.reduce(function (best, fix) { + // Takes true branch of conditional if `fix` is better than `best` return compareModuleSpecifiers(fix, best, sourceFile, program, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; }); } + /** @returns `Comparison.LessThan` if `a` is better than `b`. */ function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { - return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + return ts.compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } @@ -148773,9 +149375,12 @@ var ts; })); return { fixes: fixes, symbolName: symbolName }; } + function jsxModeNeedsExplicitImport(jsx) { + return jsx === 2 /* React */ || jsx === 3 /* ReactNative */; + } function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -149344,6 +149949,7 @@ var ts; ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, @@ -149762,7 +150368,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_14 = function (info) { + var _loop_15 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -149789,7 +150395,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_14(info); + _loop_15(info); } }); })); @@ -151324,7 +151930,8 @@ var ts; insertBefore = ts.findChildOfKind(containingFunction, 98 /* FunctionKeyword */, sourceFile); break; case 213 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + var kind = containingFunction.typeParameters ? 29 /* LessThanToken */ : 20 /* OpenParenToken */; + insertBefore = ts.findChildOfKind(containingFunction, kind, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -152396,7 +153003,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_15 = function (i) { + var _loop_16 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -152405,7 +153012,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_15(i); + _loop_16(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); @@ -152544,7 +153151,7 @@ var ts; 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, sourceFile, context, preferences, importAdder, addClassElement); + addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /* body */ undefined); } } } @@ -152556,10 +153163,19 @@ var ts; }; } codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; - /** - * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. - */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement) { + var PreserveOptionalFlags; + (function (PreserveOptionalFlags) { + PreserveOptionalFlags[PreserveOptionalFlags["Method"] = 1] = "Method"; + PreserveOptionalFlags[PreserveOptionalFlags["Property"] = 2] = "Property"; + PreserveOptionalFlags[PreserveOptionalFlags["All"] = 3] = "All"; + })(PreserveOptionalFlags = codefix.PreserveOptionalFlags || (codefix.PreserveOptionalFlags = {})); + /** + * `addClassElement` will not be called if we can't figure out a representation for `symbol` in `enclosingDeclaration`. + * @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional, isAmbient) { + if (preserveOptional === void 0) { preserveOptional = 3 /* All */; } + if (isAmbient === void 0) { isAmbient = false; } var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -152572,7 +153188,7 @@ var ts; var modifiers = visibilityModifier ? ts.factory.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); - var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); + var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */) || isAmbient; var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { case 165 /* PropertySignature */: @@ -152587,7 +153203,7 @@ var ts; } } addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* Property */) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 171 /* GetAccessor */: @@ -152608,14 +153224,14 @@ var ts; var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -152636,7 +153252,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1, "One declaration implies one signature"); var signature = signatures[0]; - outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : body || createStubbedMethodBody(quotePreference)); break; } for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) { @@ -152647,21 +153263,22 @@ var ts; if (!ambient) { if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(quotePreference, signature, modifiers, name, createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, body || createStubbedMethodBody(quotePreference)); } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional && !!(preserveOptional & 1 /* Method */), modifiers, quotePreference, body)); } } break; } function outputMethod(quotePreference, signature, modifiers, name, body) { - var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder); + var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional && !!(preserveOptional & 1 /* Method */), enclosingDeclaration, importAdder); if (method) addClassElement(method); } } + codefix.addNewNodeForMemberSymbol = addNewNodeForMemberSymbol; function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { var program = context.program; var checker = program.getTypeChecker(); @@ -152799,7 +153416,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -152830,7 +153447,7 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, body); } function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { if (ts.length(signatures)) { @@ -152838,10 +153455,10 @@ var ts; return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); } } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(quotePreference)); + /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { return createStubbedBody(ts.Diagnostics.Method_not_implemented.message, quotePreference); @@ -153646,7 +154263,8 @@ var ts; var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.factory.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); var mappedIntersectionType = ts.factory.createMappedTypeNode(ts.hasEffectiveReadonlyModifier(indexSignature) ? ts.factory.createModifier(144 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, - /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type); + /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type, + /*members*/ undefined); var intersectionType = ts.factory.createIntersectionTypeNode(__spreadArray(__spreadArray(__spreadArray([], ts.getAllSuperTypeNodes(container), true), [ mappedIntersectionType ], false), (otherMembers.length ? [ts.factory.createTypeLiteralNode(otherMembers)] : ts.emptyArray), true)); @@ -154322,7 +154940,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_16 = function (element) { + var _loop_17 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -154339,7 +154957,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_16(element); + _loop_17(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { @@ -156194,7 +156812,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_18 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -156234,7 +156852,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_18(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -156889,17 +157507,17 @@ var ts; deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } - var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var useEsModuleSyntax = !!oldFile.externalModuleIndicator; var quotePreference = ts.getQuotePreference(oldFile, preferences); - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEsModuleSyntax, quotePreference); if (importsFromNewFile) { ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference); - var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax); + var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference); + var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); if (imports.length && body.length) { return __spreadArray(__spreadArray(__spreadArray(__spreadArray([], prologueDirectives, true), imports, true), [ 4 /* NewLineTrivia */ @@ -156923,10 +157541,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_18 = function (sourceFile) { + var _loop_19 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_19 = function (statement) { + var _loop_20 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -156948,12 +157566,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_19(statement); + _loop_20(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_18(sourceFile); + _loop_19(sourceFile); } } function getNamespaceLikeImport(node) { @@ -157146,7 +157764,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -157171,7 +157789,7 @@ var ts; continue; var top = getTopLevelDeclarationStatement(decl); if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEs6ModuleSyntax); + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); } if (ts.hasSyntacticModifier(decl, 512 /* Default */)) { oldFileDefault = name; @@ -157181,7 +157799,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEsModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -158317,7 +158935,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -158346,7 +158964,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_20(i); + _loop_21(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -160108,6 +160726,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); + if (!ts.Rename.nodeIsEligibleForRename(node)) + return undefined; if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; return [openingElement, closingElement].map(function (node) { @@ -164486,6 +165106,10 @@ var ts; this.hasAddedOrRemovedSymlinks = true; } }; + /* @internal */ + Project.prototype.onDiscoveredSymlink = function () { + this.hasAddedOrRemovedSymlinks = true; + }; /** * Updates set of files that contribute to this project * @returns: true if set of files in the project stays the same and false - otherwise. @@ -170818,11 +171442,13 @@ var ts; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file)); - if (!simplifiedResult) - return locations; var defaultProject = this.getDefaultProject(args); var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.checkDefined(this.projectService.getScriptInfo(file))); + if (!renameInfo.canRename) + return simplifiedResult ? { info: renameInfo, locs: [] } : []; + var locations = combineProjectOutputForRenameLocations(projects, defaultProject, { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file)); + if (!simplifiedResult) + return locations; return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; Session.prototype.mapRenameInfo = function (info, scriptInfo) { diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 7f87f0af9d60c..1885ae3396e04 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -973,6 +973,8 @@ declare namespace ts { readonly nameType?: TypeNode; readonly questionToken?: QuestionToken | PlusToken | MinusToken; readonly type?: TypeNode; + /** Used only to produce grammar errors */ + readonly members?: NodeArray; } export interface LiteralTypeNode extends TypeNode { readonly kind: SyntaxKind.LiteralType; @@ -3420,8 +3422,8 @@ declare namespace ts { updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; - updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; + updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode; @@ -4040,6 +4042,7 @@ declare namespace ts { readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; + readonly includeCompletionsWithClassMemberSnippets?: boolean; readonly allowIncompleteCompletions?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -6367,23 +6370,28 @@ declare namespace ts { isIncomplete?: true; entries: CompletionEntry[]; } - interface CompletionEntryData { - /** The file name declaring the export's module symbol, if it was an external module */ - fileName?: string; - /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ - ambientModuleName?: string; - /** True if the export was found in the package.json AutoImportProvider */ - isPackageJsonImport?: true; + interface CompletionEntryDataAutoImport { /** * The name of the property or export in the module's symbol table. Differs from the completion name * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. */ exportName: string; - /** - * Set for auto imports with eagerly resolved module specifiers. - */ moduleSpecifier?: string; + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + } + interface CompletionEntryDataUnresolved extends CompletionEntryDataAutoImport { + /** The key in the `ExportMapCache` where the completion entry's `SymbolExportInfo[]` is found */ + exportMapKey: string; + } + interface CompletionEntryDataResolved extends CompletionEntryDataAutoImport { + moduleSpecifier: string; } + type CompletionEntryData = CompletionEntryDataUnresolved | CompletionEntryDataResolved; interface CompletionEntry { name: string; kind: ScriptElementKind; @@ -6973,9 +6981,9 @@ declare namespace ts { /** @deprecated Use `factory.updateIndexedAccessTypeNode` or the factory supplied by your transformation context instead. */ const updateIndexedAccessTypeNode: (node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) => IndexedAccessTypeNode; /** @deprecated Use `factory.createMappedTypeNode` or the factory supplied by your transformation context instead. */ - const createMappedTypeNode: (readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined) => MappedTypeNode; + const createMappedTypeNode: (readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined) => MappedTypeNode; /** @deprecated Use `factory.updateMappedTypeNode` or the factory supplied by your transformation context instead. */ - const updateMappedTypeNode: (node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined) => MappedTypeNode; + const updateMappedTypeNode: (node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined) => MappedTypeNode; /** @deprecated Use `factory.createLiteralTypeNode` or the factory supplied by your transformation context instead. */ const createLiteralTypeNode: (literal: LiteralExpression | BooleanLiteral | PrefixUnaryExpression | NullLiteral) => LiteralTypeNode; /** @deprecated Use `factory.updateLiteralTypeNode` or the factory supplied by your transformation context instead. */ diff --git a/lib/typescript.js b/lib/typescript.js index 30ff78493ccd0..6076298b6efed 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -21,7 +21,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -294,7 +294,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.5.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -323,21 +323,24 @@ var ts; return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; - })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { + })(NativeCollections || (NativeCollections = {})); + /* @internal */ + ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); + /* @internal */ + ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); + /* @internal */ function getCollectionImplementation(name, nativeFactory, shimFactory) { var _a; // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it. - var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator); + var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); if (constructor) return constructor; throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation."); } - ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); - ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { function getIterator(iterable) { if (iterable) { if (isArray(iterable)) @@ -2742,6 +2745,10 @@ var ts; return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } Debug.formatSyntaxKind = formatSyntaxKind; + function formatSnippetKind(kind) { + return formatEnum(kind, ts.SnippetKind, /*isFlags*/ false); + } + Debug.formatSnippetKind = formatSnippetKind; function formatNodeFlags(flags) { return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true); } @@ -4658,6 +4665,13 @@ var ts; ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ + var MemberOverrideStatus; + (function (MemberOverrideStatus) { + MemberOverrideStatus[MemberOverrideStatus["Ok"] = 0] = "Ok"; + MemberOverrideStatus[MemberOverrideStatus["NeedsOverride"] = 1] = "NeedsOverride"; + MemberOverrideStatus[MemberOverrideStatus["HasInvalidOverride"] = 2] = "HasInvalidOverride"; + })(MemberOverrideStatus = ts.MemberOverrideStatus || (ts.MemberOverrideStatus = {})); + /* @internal */ var UnionReduction; (function (UnionReduction) { UnionReduction[UnionReduction["None"] = 0] = "None"; @@ -5053,8 +5067,6 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable"; - /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 468598819] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask"; @@ -5067,6 +5079,10 @@ var ts; TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["IncludesInstantiable"] = 33554432] = "IncludesInstantiable"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check @@ -5306,7 +5322,7 @@ var ts; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - // Starting with node12, node's module resolver has significant departures from tranditional cjs resolution + // Starting with node12, node's module resolver has significant departures from traditional cjs resolution // to better support ecmascript modules and their use within node - more features are still being added, so // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12` // version-anchored resolution target @@ -5639,6 +5655,15 @@ var ts; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax + /* @internal */ + var SnippetKind; + (function (SnippetKind) { + SnippetKind[SnippetKind["TabStop"] = 0] = "TabStop"; + SnippetKind[SnippetKind["Placeholder"] = 1] = "Placeholder"; + SnippetKind[SnippetKind["Choice"] = 2] = "Choice"; + SnippetKind[SnippetKind["Variable"] = 3] = "Variable"; + })(SnippetKind = ts.SnippetKind || (ts.SnippetKind = {})); var EmitFlags; (function (EmitFlags) { EmitFlags[EmitFlags["None"] = 0] = "None"; @@ -7932,7 +7957,7 @@ var ts; } } function readDirectory(path, extensions, excludes, includes, depth) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve @@ -8017,6 +8042,11 @@ var ts; } return sys; })(); + /*@internal*/ + function setSys(s) { + ts.sys = s; + } + ts.setSys = setSys; if (ts.sys && ts.sys.getEnvironmentVariable) { setCustomPollingValues(ts.sys); ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) @@ -8327,6 +8357,7 @@ var ts; Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."), Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), + _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8868,6 +8899,9 @@ var ts; Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), 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}'."), @@ -8974,6 +9008,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), 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}'."), @@ -9526,6 +9561,8 @@ var ts; If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."), + A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."), + JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."), 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_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."), @@ -9581,7 +9618,7 @@ var ts; Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."), This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), @@ -9629,6 +9666,7 @@ var ts; Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"), Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), + Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), 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_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -9643,7 +9681,7 @@ var ts; 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"), + Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"), Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), @@ -19822,6 +19860,8 @@ var ts; case ts.ModuleKind.ES2020: case ts.ModuleKind.ES2022: case ts.ModuleKind.ESNext: + case ts.ModuleKind.Node12: + case ts.ModuleKind.NodeNext: return true; default: return false; @@ -20186,7 +20226,7 @@ var ts; } ts.getRegexFromPattern = getRegexFromPattern; /** @param path directory of the tsconfig.json */ - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -20200,9 +20240,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - if (directoryExists(basePath)) { - visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); - } + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -20307,10 +20345,14 @@ var ts; var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { case ".js" /* Js */: + case ".cjs" /* Cjs */: + case ".mjs" /* Mjs */: return 1 /* JS */; case ".jsx" /* Jsx */: return 2 /* JSX */; case ".ts" /* Ts */: + case ".cts" /* Cts */: + case ".mts" /* Mts */: return 3 /* TS */; case ".tsx" /* Tsx */: return 4 /* TSX */; @@ -20929,6 +20971,10 @@ var ts; return node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; + function escapeSnippetText(text) { + return text.replace(/\$/gm, "\\$"); + } + ts.escapeSnippetText = escapeSnippetText; })(ts || (ts = {})); /* @internal */ var ts; @@ -23086,24 +23132,26 @@ var ts; : node; } // @api - function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { + function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { var node = createBaseNode(194 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; node.questionToken = questionToken; node.type = type; + node.members = members && createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api - function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) { + function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) { return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type - ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node) + || node.members !== members + ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } // @api @@ -27130,6 +27178,25 @@ var ts; } } ts.moveEmitHelpers = moveEmitHelpers; + /** + * Gets the SnippetElement of a node. + */ + /* @internal */ + function getSnippetElement(node) { + var _a; + return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement; + } + ts.getSnippetElement = getSnippetElement; + /** + * Sets the SnippetElement of a node. + */ + /* @internal */ + function setSnippetElement(node, snippet) { + var emitNode = getOrCreateEmitNode(node); + emitNode.snippetElement = snippet; + return node; + } + ts.setSnippetElement = setSnippetElement; /* @internal */ function ignoreSourceNewlines(node) { getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */; @@ -29976,7 +30043,8 @@ var ts; visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) || + visitNodes(cbNode, cbNodes, node.members); case 195 /* LiteralType */: return visitNode(cbNode, node.literal); case 196 /* NamedTupleMember */: @@ -32110,7 +32178,10 @@ var ts; case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected); case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected); case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); - case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); + case 16 /* Parameters */: + return ts.isKeyword(token()) + ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_parameter_name, ts.tokenToString(token())) + : parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected); case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected); case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected); @@ -32866,8 +32937,9 @@ var ts; } var type = parseTypeAnnotation(); parseSemicolon(); + var members = parseList(4 /* TypeMembers */, parseTypeMember); parseExpected(19 /* CloseBraceToken */); - return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos); + return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } function parseTupleElementType() { var pos = getNodePos(); @@ -36154,16 +36226,21 @@ var ts; var pos = getNodePos(); parseExpected(129 /* AssertKeyword */); var openBracePosition = scanner.getTokenPos(); - parseExpected(18 /* OpenBraceToken */); - var multiLine = scanner.hasPrecedingLineBreak(); - var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); - if (!parseExpected(19 /* CloseBraceToken */)) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { - ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + if (parseExpected(18 /* OpenBraceToken */)) { + var multiLine = scanner.hasPrecedingLineBreak(); + var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); + if (!parseExpected(19 /* CloseBraceToken */)) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { + ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + } } + return finishNode(factory.createAssertClause(elements, multiLine), pos); + } + else { + var elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false); + return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos); } - return finishNode(factory.createAssertClause(elements, multiLine), pos); } function tokenAfterImportDefinitelyProducesImportDeclaration() { return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */; @@ -37058,8 +37135,9 @@ var ts; return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); - var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */ + || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference(); var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } @@ -38148,7 +38226,7 @@ var ts; var ts; (function (ts) { /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1 /* Preserve */, "react-native": 3 /* ReactNative */, @@ -38285,6 +38363,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: "false", }, { name: "excludeDirectories", @@ -38320,11 +38399,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, + defaultValueDescription: "false", }, { name: "help", shortName: "?", - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "watch", @@ -38334,6 +38415,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, + defaultValueDescription: "false", }, { name: "preserveWatchOutput", @@ -38341,7 +38423,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "listFiles", @@ -38354,7 +38436,8 @@ var ts; name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, - description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included + description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: "false", }, { name: "listEmittedFiles", @@ -38425,7 +38508,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, - description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it + description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: "false", }, { name: "locale", @@ -38470,6 +38554,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, + defaultValueDescription: "false", }, { name: "version", @@ -38478,6 +38563,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: "false", }, { name: "init", @@ -38485,6 +38571,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: "false", }, { name: "project", @@ -38502,7 +38589,8 @@ var ts; shortName: "b", showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: "false", }, { name: "showConfig", @@ -38510,7 +38598,8 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, - description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: "false", }, { name: "listFilesOnly", @@ -38519,7 +38608,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, isCommandLineOnly: true, - description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: "false", }, // Basic ts.targetOptionDeclaration, @@ -38639,7 +38729,6 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, transpileOptionValue: undefined, - defaultValueDescription: "n/a" }, { name: "outDir", @@ -38650,7 +38739,6 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files, - defaultValueDescription: "n/a" }, { name: "rootDir", @@ -38807,6 +38895,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: "false", }, { name: "alwaysStrict", @@ -38839,7 +38928,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined + description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: "false", }, { name: "noImplicitReturns", @@ -38855,21 +38945,24 @@ var ts; affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements + description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: "false", }, { name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Include_undefined_in_index_signature_results + description: ts.Diagnostics.Include_undefined_in_index_signature_results, + defaultValueDescription: "false", }, { name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: "false", }, { name: "noPropertyAccessFromIndexSignature", @@ -38885,6 +38978,8 @@ var ts; type: new ts.Map(ts.getEntries({ node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, + node12: ts.ModuleResolutionKind.Node12, + nodenext: ts.ModuleResolutionKind.NodeNext, })), affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, @@ -38976,7 +39071,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "allowUmdGlobalAccess", @@ -39025,7 +39120,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators + description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, + defaultValueDescription: "false", }, { name: "emitDecoratorMetadata", @@ -39033,7 +39129,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files + description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: "false", }, // Advanced { @@ -39076,7 +39173,6 @@ var ts; category: ts.Diagnostics.Backwards_Compatibility, paramType: ts.Diagnostics.FILE, transpileOptionValue: undefined, - defaultValueDescription: "n/a", description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead, }, { @@ -39157,6 +39253,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: "false", }, { name: "disableSizeLimit", @@ -39171,21 +39268,24 @@ var ts; type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects + description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: "false", }, { name: "disableSolutionSearching", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing + description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: "false", }, { name: "disableReferencedProjectLoad", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript + description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: "false", }, { name: "noImplicitUseStrict", @@ -39218,7 +39318,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "declarationDir", @@ -39229,7 +39329,6 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files, - defaultValueDescription: "n/a" }, { name: "skipLibCheck", @@ -39311,6 +39410,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: "false", }, { name: "keyofStringsOnly", @@ -39358,27 +39458,31 @@ var ts; shortName: "v", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "dry", shortName: "d", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "force", shortName: "f", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", } ]; /* @internal */ @@ -39391,10 +39495,12 @@ var ts; */ name: "enableAutoDiscovery", type: "boolean", + defaultValueDescription: "false", }, { name: "enable", type: "boolean", + defaultValueDescription: "false", }, { name: "include", @@ -39415,6 +39521,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", + defaultValueDescription: "false", }, ]; /*@internal*/ @@ -42687,11 +42794,15 @@ var ts; if (!scope || !scope.packageJsonContent.exports) { return undefined; } + if (typeof scope.packageJsonContent.name !== "string") { + return undefined; + } var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry - if (scope.packageJsonContent.name !== parts[1]) { + var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } - var trailingParts = parts.slice(2); + var trailingParts = parts.slice(nameParts.length); return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : "." + ts.directorySeparator + trailingParts.join(ts.directorySeparator), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { @@ -45830,6 +45941,7 @@ var ts; case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: case 172 /* SetAccessor */: + case 169 /* ClassStaticBlockDeclaration */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -47210,6 +47322,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isPropertyAccessible: isPropertyAccessible, getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration, + getMemberOverrideModifierStatus: getMemberOverrideModifierStatus, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -47453,6 +47566,21 @@ var ts; var enumRelation = new ts.Map(); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + // Extensions suggested for path imports when module resolution is node12 or higher. + // The first element of each tuple is the extension a file has. + // The second element of each tuple is the extension that should be used in a path import. + // e.g. if we want to import file `foo.mts`, we should write `import {} from "./foo.mjs". + var suggestedExtensions = [ + [".mts", ".mjs"], + [".ts", ".js"], + [".cts", ".cjs"], + [".mjs", ".mjs"], + [".js", ".js"], + [".cjs", ".cjs"], + [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], + [".jsx", ".jsx"], + [".json", ".json"], + ]; initializeTypeChecker(); return checker; function getJsxNamespace(location) { @@ -48169,11 +48297,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, issueSuggestions) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, issueSuggestions); + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, issueSuggestions) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { var _a, _b, _c; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; @@ -48500,7 +48628,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (issueSuggestions && suggestionCount < maximumSuggestionCount) { + if (suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -48509,7 +48637,9 @@ var ts; if (suggestion) { var suggestionName = symbolToString(suggestion); var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); - var message = isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; + var message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 + : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 + : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { @@ -48954,6 +49084,10 @@ var ts; function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === ts.ModuleKind.ESNext && targetMode === ts.ModuleKind.CommonJS; } + function isOnlyImportedAsDefault(usage) { + var usageMode = getUsageModeForExpression(usage); + return usageMode === ts.ModuleKind.ESNext && ts.endsWith(usage.text, ".json" /* Json */); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { var usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== undefined) { @@ -49004,8 +49138,9 @@ var ts; exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); + var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier); - if (!exportDefaultSymbol && !hasSyntheticDefault) { + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); @@ -49019,7 +49154,7 @@ var ts; reportNonDefaultExport(moduleSymbol, node); } } - else if (hasSyntheticDefault) { + else if (hasSyntheticDefault || hasDefaultOnly) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); @@ -49144,7 +49279,7 @@ var ts; var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); - if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } @@ -49503,7 +49638,7 @@ var ts; if (name.kind === 79 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true, false)); if (!symbol) { return getMergedSymbol(symbolFromJSPrototype); } @@ -49538,21 +49673,28 @@ var ts; var namespaceName = getFullyQualifiedName(namespace); var declarationName = ts.declarationNameToString(right); var suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); - var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); - var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); - var canSuggestTypeof = containingQualifiedName && !ts.isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (suggestionForNonexistentModule) { error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + return undefined; } - else if (canSuggestTypeof) { + var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); + var canSuggestTypeof = globalObjectType // <-- can't pull on types if global types aren't initialized yet + && (meaning & 788968 /* Type */) + && containingQualifiedName + && !ts.isTypeOfExpression(containingQualifiedName.parent) + && tryGetQualifiedNameAsValue(containingQualifiedName); + if (canSuggestTypeof) { error(containingQualifiedName, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.entityNameToString(containingQualifiedName)); + return undefined; } - else if (meaning & 1920 /* Namespace */ && exportedTypeSymbol && ts.isQualifiedName(name.parent)) { - error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); - } - else { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + if (meaning & 1920 /* Namespace */ && ts.isQualifiedName(name.parent)) { + var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); + if (exportedTypeSymbol) { + error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); + return undefined; + } } + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); } return undefined; } @@ -49654,7 +49796,7 @@ var ts; : undefined; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - var _a, _b, _c, _d, _e, _f; + var _a, _b, _c, _d, _e, _f, _g; if (isForAugmentation === void 0) { isForAugmentation = false; } if (ts.startsWith(moduleReference, "@types/")) { var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -49674,7 +49816,8 @@ var ts; ((_d = ts.findAncestor(location, ts.isExportDeclaration)) === null || _d === void 0 ? void 0 : _d.moduleSpecifier) || ((_e = (ts.isModuleDeclaration(location) ? location : location.parent && ts.isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)) === null || _e === void 0 ? void 0 : _e.name) || ((_f = (ts.isLiteralImportTypeNode(location) ? location : undefined)) === null || _f === void 0 ? void 0 : _f.argument.literal); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : undefined); // TODO: GH#18217 + var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -49687,6 +49830,9 @@ var ts; if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) { error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); } + if (mode === ts.ModuleKind.ESNext && compilerOptions.resolveJsonModule && resolvedModule.extension === ".json" /* Json */) { + error(errorNode, ts.Diagnostics.JSON_imports_are_experimental_in_ES_module_mode_imports); + } } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); @@ -49737,6 +49883,10 @@ var ts; } else { var tsExtension = ts.tryExtractTSExtension(moduleReference); + var isExtensionlessRelativePathImport = ts.pathIsRelative(moduleReference) && !ts.hasExtension(moduleReference); + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var resolutionIsNode12OrNext = moduleResolutionKind === ts.ModuleResolutionKind.Node12 || + moduleResolutionKind === ts.ModuleResolutionKind.NodeNext; if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension); @@ -49756,6 +49906,19 @@ var ts; ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } + else if (mode === ts.ModuleKind.ESNext && resolutionIsNode12OrNext && isExtensionlessRelativePathImport) { + var absoluteRef_1 = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(currentSourceFile.path)); + var suggestedExt = (_g = suggestedExtensions.find(function (_a) { + var actualExt = _a[0], _importExt = _a[1]; + return host.fileExists(absoluteRef_1 + actualExt); + })) === null || _g === void 0 ? void 0 : _g[1]; + if (suggestedExt) { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + } + else { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -49825,40 +49988,50 @@ var ts; error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } - if (ts.getESModuleInterop(compilerOptions)) { - var referenceParent = referencingLocation.parent; - if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || - ts.isImportCall(referenceParent)) { - var type = getTypeOfSymbol(symbol); + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var reference = ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier; + var type = getTypeOfSymbol(symbol); + var defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); + if (defaultOnlyType) { + return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); + } + if (ts.getESModuleInterop(compilerOptions)) { 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, ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier); - // 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 = new ts.Map(symbol.members); - if (symbol.exports) - result.exports = new ts.Map(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.indexInfos); - return result; + if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); + return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } } } } return symbol; } + /** + * Create a new symbol which has the module's type less the call and construct signatures + */ + function cloneTypeAsModuleType(symbol, moduleType, referenceParent) { + 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 = new ts.Map(symbol.members); + if (symbol.exports) + result.exports = new ts.Map(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.indexInfos); + return result; + } function hasExportAssignmentSymbol(moduleSymbol) { return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } @@ -49887,8 +50060,8 @@ var ts; if (exportEquals !== moduleSymbol) { var type = getTypeOfSymbol(exportEquals); if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { - getPropertiesOfType(type).forEach(function (symbol) { - cb(symbol, symbol.escapedName); + forEachPropertyOfType(type, function (symbol, escapedName) { + cb(symbol, escapedName); }); } } @@ -50220,12 +50393,15 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + if (isNamedMember(symbol, id)) { (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } + function isNamedMember(member, escapedName) { + return !isReservedMemberName(escapedName) && symbolIsValue(member); + } function getNamedOrIndexSignatureMembers(members) { var result = getNamedMembers(members); var index = getIndexSymbolFromSymbolTable(members); @@ -51100,7 +51276,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined; var templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), context); - var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode); + var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } @@ -57058,6 +57234,16 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function forEachPropertyOfType(type, action) { + type = getReducedApparentType(type); + if (type.flags & 3670016 /* StructuredType */) { + resolveStructuredTypeMembers(type).members.forEach(function (symbol, escapedName) { + if (isNamedMember(symbol, escapedName)) { + action(symbol, escapedName); + } + }); + } + } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { var list = obj.properties; return list.some(function (property) { @@ -57994,7 +58180,7 @@ var ts; return false; switch (node.kind) { case 79 /* Identifier */: - return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; case 166 /* PropertyDeclaration */: case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: @@ -59343,6 +59529,8 @@ var ts; // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { includes |= flags & 205258751 /* IncludesMask */; + if (flags & 465829888 /* Instantiable */) + includes |= 33554432 /* IncludesInstantiable */; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { @@ -59451,7 +59639,7 @@ var ts; var _loop_16 = function () { i--; var t = types[i]; - if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) { + if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { ts.orderedRemoveItemAt(types, i); } }; @@ -59556,7 +59744,7 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + var objectFlags = (includes & 36323363 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | (includes & 2097152 /* Intersection */ ? 33554432 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } @@ -60533,12 +60721,6 @@ var ts; } return type[cache] = type; } - function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { - var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); - var checkType = type.checkType; - var extendsType = type.extendsType; - return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); - } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -60847,6 +61029,10 @@ var ts; } return result; } + function isDistributionDependent(root) { + return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || + isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType)); + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -61646,7 +61832,9 @@ var ts; return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { if (!type.declaration.nameType) { - if (isArrayType(t)) { + var constraint = void 0; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && + (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, ts.or(isArrayType, isTupleType))) { return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); } if (isGenericTupleType(t)) { @@ -63186,13 +63374,12 @@ var ts; traceUnionsOrIntersectionsTooLarge(source, target); var result = 0 /* False */; var saveErrorInfo = captureErrorCalculationState(); - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { - result = getConstituentCount(source) * getConstituentCount(target) >= 4 ? - recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags) : - structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) { + // We skip caching when source or target is a union with no more than three constituents. + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + } + else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { + result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags); } if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { @@ -63649,19 +63836,19 @@ var ts; var maybeStart = maybeCount; maybeKeys[maybeCount] = id; maybeCount++; + var saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { sourceStack[sourceDepth] = source; sourceDepth++; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) + expandingFlags |= 1 /* Source */; } if (recursionFlags & 2 /* Target */) { targetStack[targetDepth] = target; targetDepth++; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) + expandingFlags |= 2 /* Target */; } - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) - expandingFlags |= 1 /* Source */; - if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) - expandingFlags |= 2 /* Target */; var originalHandler; var propagatingVarianceFlags = 0; if (outofbandVarianceMarkerHandler) { @@ -63685,13 +63872,13 @@ var ts; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } - expandingFlags = saveExpandingFlags; if (recursionFlags & 1 /* Source */) { sourceDepth--; } if (recursionFlags & 2 /* Target */) { targetDepth--; } + expandingFlags = saveExpandingFlags; if (result) { if (result === -1 /* True */ || (sourceDepth === 0 && targetDepth === 0)) { if (result === -1 /* True */ || result === 3 /* Maybe */) { @@ -63932,7 +64119,7 @@ var ts; originalErrorInfo = undefined; } } - else if (isGenericMappedType(target)) { + else if (isGenericMappedType(target) && relation !== identityRelation) { // Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`. var keysRemapped = !!target.declaration.nameType; var templateType = getTemplateTypeFromMappedType(target); @@ -63996,32 +64183,28 @@ var ts; } } else if (target.flags & 16777216 /* Conditional */) { - var c = target; - // Check if the conditional is always true or always false but still deferred for distribution purposes - var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); - var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); - // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, - // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when - // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, - // to which `{x: string | number, y: string | number}` isn't assignable) - var distributionMapper = void 0; - var checkVar = getActualTypeVariable(c.root.checkType); - if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { - var newParam = cloneTypeParameter(checkVar); - distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); - newParam.mapper = distributionMapper; - } - // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) - var expanding = isDeeplyNestedType(target, targetStack, targetDepth); - var localResult = expanding ? 3 /* Maybe */ : undefined; - if (skipTrue || expanding || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false))) { - if (!skipFalse && !expanding) { - localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); - } - } - if (localResult) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { resetErrorInfo(saveErrorInfo); - return localResult; + return 3 /* Maybe */; + } + var c = target; + // We check for a relationship to a conditional type target only when the conditional type has no + // 'infer' positions and is not distributive or is distributive but doesn't reference the check type + // parameter in either of the result types. + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) { + // Check if the conditional is always true or always false but still deferred for distribution purposes. + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + if (result = skipTrue ? -1 /* True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false)) { + result &= skipFalse ? -1 /* True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + } } } else if (target.flags & 134217728 /* TemplateLiteral */) { @@ -64033,8 +64216,7 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_9 = inferTypesFromTemplateLiteralType(source, target); - if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* True */; } } @@ -64092,33 +64274,34 @@ var ts; } } else if (source.flags & 16777216 /* Conditional */) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { + resetErrorInfo(saveErrorInfo); + return 3 /* Maybe */; + } if (target.flags & 16777216 /* Conditional */) { - // If one of the conditionals under comparison seems to be infinitely expanding, stop comparing it - back out, try - // the constraint, and failing that, give up trying to relate the two. This is the only way we can handle recursive conditional - // types, which might expand forever. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth) && !isDeeplyNestedType(target, targetStack, targetDepth)) { - // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if - // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, - // and Y1 is related to Y2. - var sourceParams = source.root.inferTypeParameters; - var sourceExtends = source.extendsType; - var mapper = void 0; - if (sourceParams) { - // If the source has infer type parameters, we instantiate them in the context of the target - var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); - sourceExtends = instantiateType(sourceExtends, ctx.mapper); - mapper = ctx.mapper; - } - if (isTypeIdenticalTo(sourceExtends, target.extendsType) && - (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { - if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + var sourceParams = source.root.inferTypeParameters; + var sourceExtends = source.extendsType; + var mapper = void 0; + if (sourceParams) { + // If the source has infer type parameters, we instantiate them in the context of the target + var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); + sourceExtends = instantiateType(sourceExtends, ctx.mapper); + mapper = ctx.mapper; + } + if (isTypeIdenticalTo(sourceExtends, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { + if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64133,17 +64316,13 @@ var ts; } } } - // We'll repeatedly decompose source side conditionals if they're recursive - check if we've already recured on the constraint a lot and, if so, bail - // on the comparison. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth)) { - // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` - // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). - var defaultConstraint = getDefaultConstraintOfConditionalType(source); - if (defaultConstraint) { - if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` + // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64232,9 +64411,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_10) { - return result_10; + var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_9) { + return result_9; } } } @@ -64306,13 +64485,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_11; + var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { + if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); + return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); } } } @@ -65252,14 +65431,15 @@ var ts; // `type A = null extends T ? [A>] : [T]` // has expanded into `[A>>>>>]` // in such cases we need to terminate the expansion, and we do so here. - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5) { + function isDeeplyNestedType(type, stack, depth, maxDepth) { + if (maxDepth === void 0) { maxDepth = 5; } + if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; for (var i = 0; i < depth; i++) { if (getRecursionIdentity(stack[i]) === identity_1) { count++; - if (count >= 5) { + if (count >= maxDepth) { return true; } } @@ -66000,7 +66180,8 @@ var ts; (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { var newName = "arg" + param.parent.parameters.indexOf(param); - errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + var typeName = ts.declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); return; } diagnostic = declaration.dotDotDotToken ? @@ -66394,6 +66575,10 @@ var ts; inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : undefined; } + function isTypeMatchedByTemplateLiteralType(source, target) { + var inferences = inferTypesFromTemplateLiteralType(source, target); + return !!inferences && ts.every(inferences, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); }); + } function getStringLikeTypeForType(type) { return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); } @@ -67170,17 +67355,16 @@ var ts; var inferredType = void 0; var signature = context.signature; if (signature) { - var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + var inferredCovariantType_1 = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - var inferredContravariantType = getContravariantInference(inference); // If we have both co- and contra-variant inferences, we prefer the contra-variant inference - // unless the co-variant inference is a subtype and not 'never'. - inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && - isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? - inferredCovariantType : inferredContravariantType; + // unless the co-variant inference is a subtype of some contra-variant inference and not 'never'. + inferredType = inferredCovariantType_1 && !(inferredCovariantType_1.flags & 131072 /* Never */) && + ts.some(inference.contraCandidates, function (t) { return isTypeSubtypeOf(inferredCovariantType_1, t); }) ? + inferredCovariantType_1 : getContravariantInference(inference); } - else if (inferredCovariantType) { - inferredType = inferredCovariantType; + else if (inferredCovariantType_1) { + inferredType = inferredCovariantType_1; } else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -67281,8 +67465,7 @@ var ts; if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), - /*excludeGlobals*/ false, - /*issueSuggestions*/ true) || unknownSymbol; + /*excludeGlobals*/ false) || unknownSymbol; } return links.resolvedSymbol; } @@ -67299,8 +67482,11 @@ var ts; function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 79 /* Identifier */: - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + if (!ts.isThisInTypeQuery(node)) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + } + // falls through case 108 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); case 229 /* NonNullExpression */: @@ -67480,8 +67666,9 @@ var ts; // constituent types keyed by the literal types of the property by that name in each constituent type. function getKeyPropertyName(unionType) { var types = unionType.types; - // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + // We only construct maps for unions with many non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */ || + ts.countWhere(types, function (t) { return !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */)); }) < 10) { return undefined; } if (unionType.keyPropertyName === undefined) { @@ -67514,7 +67701,7 @@ var ts; var keyPropertyName = getKeyPropertyName(unionType); var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 294 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); - var propType = propNode && getTypeOfExpression(propNode.initializer); + var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } function isOrContainsMatchingReference(source, target) { @@ -67930,7 +68117,7 @@ var ts; mapType(type, mapper); } function getConstituentCount(type) { - return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; + return type.flags & 1048576 /* Union */ ? type.types.length : 1; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -69428,7 +69615,7 @@ var ts; return parent.kind === 205 /* PropertyAccessExpression */ || parent.kind === 207 /* CallExpression */ && parent.expression === node || parent.kind === 206 /* ElementAccessExpression */ && parent.expression === node && - !(isGenericTypeWithoutNullableConstraint(type) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); + !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); @@ -70749,7 +70936,7 @@ var ts; return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 294 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -71304,6 +71491,10 @@ var ts; function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { + if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) { + return links.resolvedType = errorType; + } links.resolvedType = checkExpression(node.expression); // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. // (It needs to be bound at class evaluation time.) @@ -72773,7 +72964,7 @@ var ts; if (relatedInfo) { ts.addRelatedInfo(resultDiagnostic, relatedInfo); } - addErrorOrSuggestion(!isUncheckedJS, resultDiagnostic); + addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && @@ -72846,7 +73037,19 @@ var ts; // 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 // So the table *contains* `x` but `x` isn't actually in scope. // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. - return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + if (symbol) + return symbol; + var candidates; + if (symbols === globals) { + var primitives = ts.mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], function (s) { return symbols.has((s.charAt(0).toUpperCase() + s.slice(1))) + ? createSymbol(524288 /* TypeAlias */, s) + : undefined; }); + candidates = primitives.concat(ts.arrayFrom(symbols.values())); + } + else { + candidates = ts.arrayFrom(symbols.values()); + } + return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), candidates, meaning); }); return result; } @@ -75012,11 +75215,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } } return createPromiseReturnType(node, anyType); } + function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.parent = originalSymbol; + newSymbol.nameType = getStringLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + return createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + } + function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { + var hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier); + if (hasDefaultOnly && type && !isErrorType(type)) { + var synthType = type; + if (!synthType.defaultOnlyType) { + var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_4; + } + return synthType.defaultOnlyType; + } + return undefined; + } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { var _a; if (allowSyntheticDefaultImports && type && !isErrorType(type)) { @@ -75025,14 +75250,8 @@ var ts; var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false, moduleSpecifier); if (hasSyntheticDefault) { - var memberTable = ts.createSymbolTable(); - var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); - newSymbol.parent = originalSymbol; - newSymbol.nameType = getStringLiteralType("default"); - newSymbol.target = resolveSymbol(symbol); - memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); - var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); anonymousSymbol.type = defaultContainingObject; synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; } @@ -75740,12 +75959,12 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; + var type_5 = getBaseConstraintOfType(operandType) || operandType; // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_4.flags & 3 /* AnyOrUnknown */) { + if (type_5.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */; } - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -78335,7 +78554,9 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + if (!typeParameters) + return undefined; var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -78346,7 +78567,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); + checkIndexConstraints(type, type.symbol); checkTypeForDuplicateIndexSignatures(node); checkObjectTypeForDuplicateDeclarations(node); } @@ -78441,6 +78662,7 @@ var ts; checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { + checkGrammarMappedType(node); checkSourceElement(node.typeParameter); checkSourceElement(node.nameType); checkSourceElement(node.type); @@ -78457,6 +78679,12 @@ var ts; checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); } } + function checkGrammarMappedType(node) { + var _a; + if ((_a = node.members) === null || _a === void 0 ? void 0 : _a.length) { + return grammarErrorOnNode(node.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + } function checkThisType(node) { getTypeFromThisTypeNode(node); } @@ -78834,12 +79062,12 @@ var ts; case 264 /* ImportEqualsDeclaration */: case 267 /* NamespaceImport */: case 266 /* ImportClause */: - var result_12 = 0 /* None */; + var result_11 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { - result_12 |= getDeclarationSpaces(d); + result_11 |= getDeclarationSpaces(d); }); - return result_12; + return result_11; case 253 /* VariableDeclaration */: case 202 /* BindingElement */: case 255 /* FunctionDeclaration */: @@ -81402,7 +81630,7 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type, isStaticIndex) { + function checkIndexConstraints(type, symbol, isStaticIndex) { var indexInfos = getIndexInfosOfType(type); if (indexInfos.length === 0) { return; @@ -81413,15 +81641,15 @@ var ts; checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */, /*includeNonPublic*/ true), getNonMissingTypeOfSymbol(prop)); } } - var typeDeclaration = type.symbol.valueDeclaration; + var typeDeclaration = symbol.valueDeclaration; if (typeDeclaration && ts.isClassLike(typeDeclaration)) { for (var _b = 0, _c = typeDeclaration.members; _b < _c.length; _b++) { var member = _c[_b]; // Only process instance properties with computed names here. Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. if (!ts.isStatic(member) && !hasBindableName(member)) { - var symbol = getSymbolOfNode(member); - checkIndexConstraintForProperty(type, symbol, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol)); + var symbol_3 = getSymbolOfNode(member); + checkIndexConstraintForProperty(type, symbol_3, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol_3)); } } } @@ -81708,7 +81936,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); + checkMembersForOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -81737,14 +81965,13 @@ var ts; } } if (produceDiagnostics) { - checkIndexConstraints(type); - checkIndexConstraints(staticType, /*isStaticIndex*/ true); + checkIndexConstraints(type, symbol); + checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { - var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) { var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; @@ -81756,46 +81983,71 @@ var ts; if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { - checkClassMember(param, /*memberIsParameterProperty*/ true); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, + /* memberIsParameterProperty */ true); } }); } - checkClassMember(member); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, + /* memberIsParameterProperty */ false); }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; _loop_29(member); } - function checkClassMember(member, memberIsParameterProperty) { - var hasOverride = ts.hasOverrideModifier(member); - var hasStatic = ts.isStatic(member); - var isJs = ts.isInJSFile(member); - if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { - var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); - if (!declaredProp) { - return; - } - var thisType = hasStatic ? staticType : typeWithThis; - var baseType = hasStatic ? baseStaticType : baseWithThis; - var prop = getPropertyOfType(thisType, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); - var baseClassName = typeToString(baseWithThis); - if (prop && !baseProp && hasOverride) { - var suggestion = getSuggestedSymbolForNonexistentClassMember(ts.symbolName(declaredProp), baseType); + } + /** + * @param member Existing member node to be checked. + * Note: `member` cannot be a synthetic node. + */ + function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { + if (reportErrors === void 0) { reportErrors = true; } + var declaredProp = member.name + && getSymbolAtLocation(member.name) + || getSymbolAtLocation(member); + if (!declaredProp) { + return 0 /* Ok */; + } + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, ts.hasOverrideModifier(member), ts.hasAbstractModifier(member), ts.isStatic(member), memberIsParameterProperty, ts.symbolName(declaredProp), reportErrors ? member : undefined); + } + /** + * Checks a class member declaration for either a missing or an invalid `override` modifier. + * Note: this function can be used for speculative checking, + * i.e. checking a member that does not yet exist in the program. + * An example of that would be to call this function in a completions scenario, + * when offering a method declaration as completion. + * @param errorNode The node where we should report an error, or undefined if we should not report errors. + */ + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { + var isJs = ts.isInJSFile(node); + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { + var memberEscapedName = ts.escapeLeadingUnderscores(memberName); + var thisType = memberIsStatic ? staticType : typeWithThis; + var baseType = memberIsStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, memberEscapedName); + var baseProp = getPropertyOfType(baseType, memberEscapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && memberHasOverrideModifier) { + if (errorNode) { + var suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); // Again, using symbol name: note that's different from `symbol.escapedName` suggestion ? - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } - else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { - var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); - if (hasOverride) { - return; - } - if (!baseHasAbstract) { + return 2 /* HasInvalidOverride */; + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); + if (memberHasOverrideModifier) { + return 0 /* Ok */; + } + if (!baseHasAbstract) { + if (errorNode) { var diag = memberIsParameterProperty ? isJs ? ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : @@ -81803,20 +82055,28 @@ var ts; isJs ? ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; - error(member, diag, baseClassName); + error(errorNode, diag, baseClassName); } - else if (ts.hasAbstractModifier(member) && baseHasAbstract) { - error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + return 1 /* NeedsOverride */; + } + else if (memberHasAbstractModifier && baseHasAbstract) { + if (errorNode) { + error(errorNode, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); } + return 1 /* NeedsOverride */; } } - else if (hasOverride) { + } + else if (memberHasOverrideModifier) { + if (errorNode) { var className = typeToString(type); - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } + return 2 /* HasInvalidOverride */; } + return 0 /* Ok */; } 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 @@ -81859,6 +82119,31 @@ var ts; } } } + /** + * Checks a member declaration node to see if has a missing or invalid `override` modifier. + * @param node Class-like node where the member is declared. + * @param member Member declaration node. + * Note: `member` can be a synthetic node without a parent. + */ + function getMemberOverrideModifierStatus(node, member) { + if (!member.name) { + return 0 /* Ok */; + } + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var memberHasOverrideModifier = member.parent + ? ts.hasOverrideModifier(member) + : ts.hasSyntacticModifier(member, 16384 /* Override */); + var memberName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name)); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, ts.hasAbstractModifier(member), ts.isStatic(member), + /* memberIsParameterProperty */ false, memberName); + } function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -82129,7 +82414,7 @@ var ts; var baseType = _a[_i]; checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); } - checkIndexConstraints(type); + checkIndexConstraints(type, symbol); } } checkObjectTypeForDuplicateDeclarations(node); @@ -86320,6 +86605,9 @@ var ts; } } function checkGrammarProperty(node) { + if (ts.isComputedPropertyName(node.name) && ts.isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101 /* InKeyword */) { + return grammarErrorOnNode(node.parent.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } if (ts.isClassLike(node.parent)) { if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); @@ -86339,7 +86627,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 181 /* TypeLiteral */) { + else if (ts.isTypeLiteralNode(node.parent)) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -87016,7 +87304,7 @@ var ts; return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); case 194 /* MappedType */: ts.Debug.type(node); - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 195 /* LiteralType */: ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); @@ -94852,11 +95140,11 @@ var ts; currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } - function getJsxFactoryCalleePrimitive(childrenLength) { - return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx"; + function getJsxFactoryCalleePrimitive(isStaticChildren) { + return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx"; } - function getJsxFactoryCallee(childrenLength) { - var type = getJsxFactoryCalleePrimitive(childrenLength); + function getJsxFactoryCallee(isStaticChildren) { + var type = getJsxFactoryCalleePrimitive(isStaticChildren); return getImplicitImportForName(type); } function getImplicitJsxFragmentReference() { @@ -95003,60 +95291,37 @@ var ts; return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node); } function convertJsxChildrenToChildrenPropObject(children) { + var prop = convertJsxChildrenToChildrenPropAssignment(children); + return prop && factory.createObjectLiteralExpression([prop]); + } + function convertJsxChildrenToChildrenPropAssignment(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); - if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) - ]); + if (ts.length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) { + var result_12 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_12 && factory.createPropertyAssignment("children", result_12); } var result = ts.mapDefined(children, transformJsxChildToExpression); - return !result.length ? undefined : factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) - ]); + return ts.length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined; } function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; + var childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined; var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; }); var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties; - var segments = []; - if (attrs.length) { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - } - if (children && children.length) { - var result = convertJsxChildrenToChildrenPropObject(children); - if (result) { - segments.push(result); - } - } - if (segments.length === 0) { - objectProperties = factory.createObjectLiteralExpression([]); - // When there are no attributes, React wants {} - } - else { - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments); - } - return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location); + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : + factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : ts.emptyArray); // When there are no attributes, React wants {} + return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || ts.emptyArray, isChild, location); } - function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) { + function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { + var _a; + var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); + var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; if (compilerOptions.jsx === 5 /* ReactJSXDev */) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { // isStaticChildren development flag - args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse()); + args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); // __source development flag var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos); args.push(factory.createObjectLiteralExpression([ @@ -95068,7 +95333,7 @@ var ts; args.push(factory.createThis()); } } - var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location); + var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args), location); if (isChild) { ts.startOnNewLine(element); } @@ -95076,38 +95341,9 @@ var ts; } function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; var attrs = node.attributes.properties; - if (attrs.length === 0) { - objectProperties = factory.createNull(); - // When there are no attributes, React wants "null" - } - else { - var target = ts.getEmitScriptTarget(compilerOptions); - if (target && target >= 5 /* ES2018 */) { - objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { - return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); - }))); - } - else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); - } - } - } + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs) : + factory.createNull(); // When there are no attributes, React wants "null" var callee = currentFileState.importSpecifier === undefined ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 node) @@ -95127,7 +95363,7 @@ var ts; } } return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), - /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location); + /*keyAttr*/ undefined, children, isChild, location); } function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 @@ -95140,6 +95376,36 @@ var ts; function transformJsxSpreadAttributeToSpreadAssignment(node) { return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); } + function transformJsxAttributesToObjectProps(attrs, children) { + var target = ts.getEmitScriptTarget(compilerOptions); + return target && target >= 5 /* ES2018 */ ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : + transformJsxAttributesToExpression(attrs, children); + } + function transformJsxAttributesToProps(attrs, children) { + var props = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return ts.map(attrs, function (attr) { return isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr); }); + })); + if (children) { + props.push(children); + } + return props; + } + function transformJsxAttributesToExpression(attrs, children) { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var expressions = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + expressions.unshift(factory.createObjectLiteralExpression()); + } + if (children) { + expressions.push(factory.createObjectLiteralExpression([children])); + } + return ts.singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -98555,78 +98821,17 @@ var ts; * @param node A TemplateExpression node. */ function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - // createAdd will check if each expression binds less closely than binary '+'. - // If it does, it wraps the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var expression = ts.reduceLeft(expressions, factory.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - /** - * Gets a value indicating whether we need to include the head of a TemplateExpression. - * - * @param node A TemplateExpression node. - */ - function shouldAddTemplateHead(node) { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - /** - * Adds the head of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(factory.createStringLiteral(node.head.text)); - } - /** - * Visits and adds the template spans of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateSpans(expressions, node) { + var expression = factory.createStringLiteral(node.head.text); for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { var span = _a[_i]; - expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span.literal.text.length !== 0) { - expressions.push(factory.createStringLiteral(span.literal.text)); + var args = [ts.visitNode(span.expression, visitor, ts.isExpression)]; + if (span.literal.text.length > 0) { + args.push(factory.createStringLiteral(span.literal.text)); } + expression = factory.createCallExpression(factory.createPropertyAccessExpression(expression, "concat"), + /*typeArguments*/ undefined, args); } + return ts.setTextRange(expression, node); } /** * Visits the `super` keyword @@ -108246,7 +108451,14 @@ var ts; // clear the parenthesizer rule as we ascend currentParenthesizerRule = undefined; } - function pipelineEmitWithHintWorker(hint, node) { + function pipelineEmitWithHintWorker(hint, node, allowSnippets) { + if (allowSnippets === void 0) { allowSnippets = true; } + if (allowSnippets) { + var snippet = ts.getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -108855,6 +109067,28 @@ var ts; } } // + // Snippet Elements + // + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1 /* Placeholder */: + emitPlaceholder(hint, node, snippet); + break; + case 0 /* TabStop */: + emitTabStop(snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite("${" + snippet.order + ":"); // `${2:` + pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...` + nonEscapingWrite("}"); // `}` + // `${2:...}` + } + function emitTabStop(snippet) { + nonEscapingWrite("$" + snippet.order); + } + // // Identifiers // function emitIdentifier(node) { @@ -111093,6 +111327,15 @@ var ts; function writeProperty(s) { writer.writeProperty(s); } + function nonEscapingWrite(s) { + // This should be defined in a snippet-escaping text writer. + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } + else { + writer.write(s); + } + } function writeLine(count) { if (count === void 0) { count = 1; } for (var i = 0; i < count; i++) { @@ -112362,7 +112605,7 @@ var ts; var rootResult = tryReadDirectory(rootDir, rootDirPath); var rootSymLinkResult; if (rootResult !== undefined) { - return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -113334,7 +113577,7 @@ var ts; break; case ts.FileIncludeKind.TypeReferenceDirective: (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end); - packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), getModeForResolutionAtIndex(file, index))) === null || _g === void 0 ? void 0 : _g.packageId; + packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId; break; case ts.FileIncludeKind.LibReferenceDirective: (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end); @@ -113896,15 +114139,15 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_13 = []; var i = 0; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i)); i++; - result_14.push(resolvedModule); + result_13.push(resolvedModule); } - return result_14; + return result_13; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -114196,8 +114439,8 @@ var ts; var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); }); var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile); // ensure that types resolutions are still correct - var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); - if (typeReferenceEesolutionsChanged) { + var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); + if (typeReferenceResolutionsChanged) { structureIsReused = 1 /* SafeModules */; newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions); } @@ -115485,6 +115728,21 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { + var isNightly = ts.stringContains(ts.version, "-dev"); + if (!isNightly) { + if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); + } + else if (ts.getEmitModuleKind(options) === ts.ModuleKind.NodeNext) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext"); + } + } if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } @@ -115633,7 +115891,9 @@ var ts; } } if (options.resolveJsonModule) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } // Any emit other than common js, amd, es2015 or esnext is error @@ -115961,8 +116221,8 @@ var ts; function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + function createOptionValueDiagnostic(option1, message, arg0, arg1) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1); } function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); @@ -118206,6 +118466,9 @@ var ts; else { resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile); perDirectoryResolution.set(name, mode, resolution); + if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { + resolutionHost.onDiscoveredSymlink(); + } } resolutionsInFile.set(name, mode, resolution); watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); @@ -118674,6 +118937,11 @@ var ts; } } ts.createResolutionCache = createResolutionCache; + function resolutionIsSymlink(resolution) { + var _a, _b; + return !!(((_a = resolution.resolvedModule) === null || _a === void 0 ? void 0 : _a.originalPath) || + ((_b = resolution.resolvedTypeReferenceDirective) === null || _b === void 0 ? void 0 : _b.originalPath)); + } })(ts || (ts = {})); // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ @@ -118966,9 +119234,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_14 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_14) + return result_14; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -118988,10 +119256,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_15 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_15) + return result_15; } }); }); @@ -119284,13 +119552,15 @@ var ts; if (host.fileExists(packageJsonPath)) { var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); // TODO: Inject `require` or `import` condition based on the intended import mode - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; - if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; - return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); - } - if (packageJsonContent.exports) { - return { moduleFileToTry: path, blockedByExports: true }; + if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + if (fromExports) { + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); + } + if (packageJsonContent.exports) { + return { moduleFileToTry: path, blockedByExports: true }; + } } var versionPaths = packageJsonContent.typesVersions ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -120332,6 +120602,9 @@ var ts; sourceFilesCache.set(path, false); } } + if (sourceFile) { + sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); + } return sourceFile; } return hostSourceFile.sourceFile; @@ -121288,11 +121561,11 @@ var ts; (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [state.host.realpath ? toPath(state, state.host.realpath(path)) : path, data]; - })); if (state.watch) { + state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { + var path = _a[0], data = _a[1]; + return [state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data]; + })); state.builderPrograms.set(projectPath, program); } step++; @@ -124072,28 +124345,85 @@ var ts; /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { var current = sourceFile; - outer: while (true) { + var foundToken; + var _loop_1 = function () { // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { - var child = _a[_i]; - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + var children = current.getChildren(sourceFile); + var i = ts.binarySearchKey(children, position, function (_, i) { return i; }, function (middle, _) { + // This last callback is more of a selector than a comparator - + // `EqualTo` causes the `middle` result to be returned + // `GreaterThan` causes recursion on the left of the middle + // `LessThan` causes recursion on the right of the middle + // Let's say you have 3 nodes, spanning positons + // pos: 1, end: 3 + // pos: 3, end: 3 + // pos: 3, end: 5 + // and you're looking for the token at positon 3 - all 3 of these nodes are overlapping with position 3. + // In fact, there's a _good argument_ that node 2 shouldn't even be allowed to exist - depending on if + // the start or end of the ranges are considered inclusive, it's either wholly subsumed by the first or the last node. + // Unfortunately, such nodes do exist. :( - See fourslash/completionsImport_tsx.tsx - empty jsx attributes create + // a zero-length node. + // What also you may not expect is that which node we return depends on the includePrecedingTokenAtEndPosition flag. + // Specifically, if includePrecedingTokenAtEndPosition is set, we return the 1-3 node, while if it's unset, we + // return the 3-5 node. (The zero length node is never correct.) This is because the includePrecedingTokenAtEndPosition + // flag causes us to return the first node whose end position matches the position and which produces and acceptable token + // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the + // position and whose end is greater than the position. + var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { - // If this child begins after position, then all subsequent children will as well. - break; - } - var end = child.getEnd(); - if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { - current = child; - continue outer; + return 1 /* GreaterThan */; } - else if (includePrecedingTokenAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { - return previousToken; + // first element whose start position is before the input and whose end position is after or equal to the input + if (nodeContainsPosition(children[middle])) { + if (children[middle - 1]) { + // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position + if (nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } } + return 0 /* EqualTo */; + } + // this complex condition makes us left-recur around a zero-length node when includePrecedingTokenAtEndPosition is set, rather than right-recur on it + if (includePrecedingTokenAtEndPosition && start === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; } + return -1 /* LessThan */; + }); + if (foundToken) { + return { value: foundToken }; } - return current; + if (i >= 0 && children[i]) { + current = children[i]; + return "continue-outer"; + } + return { value: current }; + }; + outer: while (true) { + var state_1 = _loop_1(); + if (typeof state_1 === "object") + return state_1.value; + switch (state_1) { + case "continue-outer": continue outer; + } + } + function nodeContainsPosition(node) { + var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + return false; + } + var end = node.getEnd(); + if (position < end || (position === end && (node.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + return true; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, node); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + foundToken = previousToken; + return true; + } + } + return false; } } /** @@ -124736,14 +125066,14 @@ var ts; return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); } ts.programContainsModules = programContainsModules; - function programContainsEs6Modules(program) { + function programContainsEsModules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } - ts.programContainsEs6Modules = programContainsEs6Modules; - function compilerOptionsIndicateEs6Modules(compilerOptions) { + ts.programContainsEsModules = programContainsEsModules; + function compilerOptionsIndicateEsModules(compilerOptions) { return !!compilerOptions.module || ts.getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ || !!compilerOptions.noEmit; } - ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + ts.compilerOptionsIndicateEsModules = compilerOptionsIndicateEsModules; function createModuleSpecifierResolutionHost(program, host) { // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. @@ -125130,9 +125460,9 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.linkText); } ts.linkTextPart = linkTextPart; - function linkNamePart(name, target) { + function linkNamePart(text, target) { return { - text: ts.getTextOfNode(name), + text: text, kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], target: { fileName: ts.getSourceFileOfNode(target).fileName, @@ -125157,20 +125487,41 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var suffix = findLinkNameEnd(link.text); + var name = ts.getTextOfNode(link.name) + link.text.slice(0, suffix); + var text = link.text.slice(suffix); var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); if (decl) { - parts.push(linkNamePart(link.name, decl)); - if (link.text) - parts.push(linkTextPart(link.text)); + parts.push(linkNamePart(name, decl)); + if (text) + parts.push(linkTextPart(text)); } else { - parts.push(linkTextPart(ts.getTextOfNode(link.name) + " " + link.text)); + parts.push(linkTextPart(name + (suffix ? "" : " ") + text)); } } parts.push(linkPart("}")); return parts; } ts.buildLinkParts = buildLinkParts; + function findLinkNameEnd(text) { + if (text.indexOf("()") === 0) + return 2; + if (text[0] !== "<") + return 0; + var brackets = 0; + var i = 0; + while (i < text.length) { + if (text[i] === "<") + brackets++; + if (text[i] === ">") + brackets--; + i++; + if (!brackets) + return i; + } + return 0; + } var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -126035,6 +126386,16 @@ var ts; return decisionFromFile !== null && decisionFromFile !== void 0 ? decisionFromFile : program.usesUriStyleNodeCoreModules; } ts.shouldUseUriStyleNodeCoreModules = shouldUseUriStyleNodeCoreModules; + function getNewLineKind(newLineCharacter) { + return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + } + ts.getNewLineKind = getNewLineKind; + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + ts.diagnosticToString = diagnosticToString; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -126074,19 +126435,24 @@ var ts; } var isDefault = exportKind === 1 /* Default */; var namedSymbol = isDefault && ts.getLocalSymbolForExportDefault(symbol) || symbol; - // A re-export merged with an export from a module augmentation can result in `symbol` - // being an external module symbol; the name it is re-exported by will be `symbolTableKey` - // (which comes from the keys of `moduleSymbol.exports`.) - var importedName = ts.isExternalModuleSymbol(namedSymbol) + // 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`. + // 2. A re-export merged with an export from a module augmentation can result in `symbol` + // being an external module symbol; the name it is re-exported by will be `symbolTableKey` + // (which comes from the keys of `moduleSymbol.exports`.) + // 3. Otherwise, we have a default/namespace import that can be imported by any name, and + // `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to + // get a better name. + var importedName = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) ? ts.unescapeLeadingUnderscores(symbolTableKey) : ts.getNameForExportedSymbol(namedSymbol, scriptTarget); var moduleName = ts.stripQuotes(moduleSymbol.name); var id = exportInfoId++; + var target = ts.skipAlias(symbol, checker); var storedSymbol = symbol.flags & 33554432 /* Transient */ ? undefined : symbol; var storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? undefined : moduleSymbol; if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); - exportInfo.add(key(importedName, symbol, moduleName, checker), { + exportInfo.add(key(importedName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { id: id, symbolTableKey: symbolTableKey, symbolName: importedName, @@ -126094,16 +126460,16 @@ var ts; moduleFile: moduleFile, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: exportKind, - targetFlags: ts.skipAlias(symbol, checker).flags, + targetFlags: target.flags, isFromPackageJson: isFromPackageJson, symbol: storedSymbol, moduleSymbol: storedModuleSymbol, }); }, - get: function (importingFile, importedName, symbol, moduleName, checker) { + get: function (importingFile, key) { if (importingFile !== usableByFileName) return; - var result = exportInfo.get(key(importedName, symbol, moduleName, checker)); + var result = exportInfo.get(key); return result === null || result === void 0 ? void 0 : result.map(rehydrateCachedInfo); }, forEach: function (importingFile, action) { @@ -126111,7 +126477,7 @@ var ts; return; exportInfo.forEach(function (info, key) { var _a = parseKey(key), symbolName = _a.symbolName, ambientModuleName = _a.ambientModuleName; - action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName); + action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName, key); }); }, releaseSymbols: function () { @@ -126176,26 +126542,16 @@ var ts; isFromPackageJson: isFromPackageJson, }; } - function key(importedName, symbol, moduleName, checker) { - var unquoted = ts.stripQuotes(moduleName); - var moduleKey = ts.isExternalModuleNameRelative(unquoted) ? "/" : unquoted; - var target = ts.skipAlias(symbol, checker); - return importedName + "|" + createSymbolKey(target) + "|" + moduleKey; + function key(importedName, symbol, ambientModuleName, checker) { + var moduleKey = ambientModuleName || ""; + return importedName + "|" + ts.getSymbolId(ts.skipAlias(symbol, checker)) + "|" + moduleKey; } function parseKey(key) { var symbolName = key.substring(0, key.indexOf("|")); var moduleKey = key.substring(key.lastIndexOf("|") + 1); - var ambientModuleName = moduleKey === "/" ? undefined : moduleKey; + var ambientModuleName = moduleKey === "" ? undefined : moduleKey; return { symbolName: symbolName, ambientModuleName: ambientModuleName }; } - function createSymbolKey(symbol) { - var key = symbol.name; - while (symbol.parent) { - key += "," + symbol.parent.name; - symbol = symbol.parent; - } - return key; - } function fileIsGlobalOnly(file) { return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; } @@ -126205,7 +126561,7 @@ var ts; } var oldFileStatementIndex = -1; var newFileStatementIndex = -1; - var _loop_1 = function (ambientModuleName) { + var _loop_2 = function (ambientModuleName) { var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); @@ -126215,9 +126571,9 @@ var ts; }; for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { var ambientModuleName = _a[_i]; - var state_1 = _loop_1(ambientModuleName); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_2(ambientModuleName); + if (typeof state_2 === "object") + return state_2.value; } return true; } @@ -126317,7 +126673,7 @@ var ts; cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, scriptTarget, checker); } checker.forEachExportAndPropertyOfModule(moduleSymbol, function (exported, key) { - if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, exported)) { + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, key)) { cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, scriptTarget, checker); } }); @@ -127637,7 +127993,7 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { - function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); return entries && convertPathCompletions(entries); @@ -127645,12 +128001,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -127660,7 +128016,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -128059,7 +128415,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_2 = function (name, kind, extension) { + var _loop_3 = function (name, kind, extension) { // 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 === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -128067,7 +128423,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_2(name, kind, extension); + _loop_3(name, kind, extension); } } } @@ -128102,7 +128458,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_3 = function (moduleName) { + var _loop_4 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -128110,7 +128466,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_3(moduleName); + _loop_4(moduleName); } } if (!foundGlobal) { @@ -128386,6 +128742,8 @@ var ts; (function (CompletionSource) { /** Completions that require `this.` insertion text */ CompletionSource["ThisProperty"] = "ThisProperty/"; + /** Auto-import that comes attached to a class member snippet */ + CompletionSource["ClassMemberSnippet"] = "ClassMemberSnippet/"; })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { @@ -128494,7 +128852,6 @@ var ts; } // If the request is a continuation of an earlier `isIncomplete` response, // we can continue it from the cached previous response. - var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a = host.getIncompleteCompletionsCache) === null || _a === void 0 ? void 0 : _a.call(host) : undefined; if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && ts.isIdentifier(previousToken)) { @@ -128506,7 +128863,7 @@ var ts; else { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.clear(); } - var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, typeChecker, compilerOptions, host, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences); if (stringCompletions) { return stringCompletions; } @@ -128520,7 +128877,7 @@ var ts; } switch (completionData.kind) { case 0 /* Data */: - var response = completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); + var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences); if (response === null || response === void 0 ? void 0 : response.isIncomplete) { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.set(response); } @@ -128540,20 +128897,19 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function completionEntryDataIsResolved(data) { + return !!(data === null || data === void 0 ? void 0 : data.moduleSpecifier); + } function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken) { - var _a; var previousResponse = cache.get(); if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var checker = program.getTypeChecker(); - var autoImportProvider = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); - var autoImportProviderChecker = autoImportProvider === null || autoImportProvider === void 0 ? void 0 : autoImportProvider.getTypeChecker(); var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, preferences, /*isForImportStatementCompletion*/ false, function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { - if (!entry.hasAction || !entry.source || !entry.data || entry.data.moduleSpecifier) { + if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) { // Not an auto import or already resolved; keep as is return entry; } @@ -128561,8 +128917,8 @@ var ts; // No longer matches typed characters; filter out return undefined; } - var _a = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)), symbol = _a.symbol, origin = _a.origin; - var info = exportMap.get(file.path, entry.name, symbol, origin.moduleSymbol.name, origin.isFromPackageJson ? autoImportProviderChecker : checker); + var origin = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)).origin; + var info = exportMap.get(file.path, entry.data.exportMapKey); var result = info && context.tryResolve(info, !ts.isExternalModuleNameRelative(ts.stripQuotes(origin.moduleSymbol.name))); if (!result) return entry; @@ -128618,7 +128974,7 @@ var ts; // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 79 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; // Verify if the file is JSX language variant if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { @@ -128630,7 +128986,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); // TODO: GH#18217 } else { @@ -128638,7 +128994,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -128744,14 +129100,16 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { - var _a; + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind) { + var _a, _b; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(replacementToken); var data; var isSnippet; + var source = getSourceFromOrigin(origin); var sourceDisplay; var hasAction; + var typeChecker = program.getTypeChecker(); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -128802,12 +129160,16 @@ var ts; isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; } } - if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { - return undefined; - } - if (originIsExport(origin) || originIsResolvedExport(origin)) { - data = originToCompletionEntryData(origin); - hasAction = !importCompletionNode; + if (preferences.includeCompletionsWithClassMemberSnippets && + preferences.includeCompletionsWithInsertText && + completionKind === 3 /* MemberLike */ && + isClassLikeMemberCompletion(symbol, location)) { + var importAdder = void 0; + (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); + if (importAdder === null || importAdder === void 0 ? void 0 : importAdder.hasFixes()) { + hasAction = true; + source = CompletionSource.ClassMemberSnippet; + } } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location); if (kind === "JSX attribute" /* jsxAttribute */ && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { @@ -128819,7 +129181,7 @@ var ts; && !(type.flags & 1048576 /* Union */ && ts.find(type.types, function (type) { return !!(type.flags & 528 /* BooleanLike */); }))) { if (type.flags & 402653316 /* StringLike */ || (type.flags & 1048576 /* Union */ && ts.every(type.types, function (type) { return !!(type.flags & (402653316 /* StringLike */ | 32768 /* Undefined */)); }))) { // If is string like or undefined use quotes - insertText = escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); + insertText = ts.escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); isSnippet = true; } else { @@ -128828,12 +129190,16 @@ var ts; } } if (useBraces_1) { - insertText = escapeSnippetText(name) + "={$1}"; + insertText = ts.escapeSnippetText(name) + "={$1}"; isSnippet = true; } - if (isSnippet) { - replacementSpan = ts.createTextSpanFromNode(location, sourceFile); - } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = originToCompletionEntryData(origin); + hasAction = !importCompletionNode; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but @@ -128847,7 +129213,7 @@ var ts; kind: kind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), sortText: sortText, - source: getSourceFromOrigin(origin), + source: source, hasAction: hasAction ? true : undefined, isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, @@ -128859,17 +129225,222 @@ var ts; data: data, }; } - function escapeSnippetText(text) { - return text.replace(/\$/gm, "\\$"); + function isClassLikeMemberCompletion(symbol, location) { + // TODO: support JS files. + if (ts.isInJSFile(location)) { + return false; + } + // Completion symbol must be for a class member. + var memberFlags = 106500 /* ClassMember */ + & 900095 /* EnumMemberExcludes */; + /* In + `class C { + | + }` + `location` is a class-like declaration. + In + `class C { + m| + }` + `location` is an identifier, + `location.parent` is a class element declaration, + and `location.parent.parent` is a class-like declaration. + In + `abstract class C { + abstract + abstract m| + }` + `location` is a syntax list (with modifiers as children), + and `location.parent` is a class-like declaration. + */ + return !!(symbol.flags & memberFlags) && + (ts.isClassLike(location) || + (location.parent && + location.parent.parent && + ts.isClassElement(location.parent) && + location === location.parent.name && + ts.isClassLike(location.parent.parent)) || + (location.parent && + ts.isSyntaxList(location) && + ts.isClassLike(location.parent))); + } + function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken) { + var classLikeDeclaration = ts.findAncestor(location, ts.isClassLike); + if (!classLikeDeclaration) { + return { insertText: name }; + } + var isSnippet; + var insertText = name; + var checker = program.getTypeChecker(); + var sourceFile = location.getSourceFile(); + var printer = createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target, + omitTrailingSemicolon: false, + newLine: ts.getNewLineKind(ts.getNewLineCharacter(options, ts.maybeBind(host, host.getNewLine))), + }); + var importAdder = ts.codefix.createImportAdder(sourceFile, program, preferences, host); + var body; + if (preferences.includeCompletionsWithSnippetText) { + isSnippet = true; + // We are adding a tabstop (i.e. `$0`) in the body of the suggested member, + // if it has one, so that the cursor ends up in the body once the completion is inserted. + // Note: this assumes we won't have more than one body in the completion nodes, which should be the case. + var emptyStatement = ts.factory.createExpressionStatement(ts.factory.createIdentifier("")); + ts.setSnippetElement(emptyStatement, { kind: 0 /* TabStop */, order: 0 }); + body = ts.factory.createBlock([emptyStatement], /* multiline */ true); + } + else { + body = ts.factory.createBlock([], /* multiline */ true); + } + var modifiers = 0 /* None */; + // Whether the suggested member should be abstract. + // e.g. in `abstract class C { abstract | }`, we should offer abstract method signatures at position `|`. + // Note: We are relying on checking if the context token is `abstract`, + // since other visibility modifiers (e.g. `protected`) should come *before* `abstract`. + // However, that is not true for the e.g. `override` modifier, so this check has its limitations. + var isAbstract = contextToken && isModifierLike(contextToken) === 126 /* AbstractKeyword */; + var completionNodes = []; + ts.codefix.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { program: program, host: host }, preferences, importAdder, + // `addNewNodeForMemberSymbol` calls this callback function for each new member node + // it adds for the given member symbol. + // We store these member nodes in the `completionNodes` array. + // Note: there might be: + // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; + // - One node; + // - More than one node if the member is overloaded (e.g. a method with overload signatures). + function (node) { + var requiredModifiers = 0 /* None */; + if (isAbstract) { + requiredModifiers |= 128 /* Abstract */; + } + if (ts.isClassElement(node) + && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node) === 1 /* NeedsOverride */) { + requiredModifiers |= 16384 /* Override */; + } + var presentModifiers = 0 /* None */; + if (!completionNodes.length) { + // Omit already present modifiers from the first completion node/signature. + if (contextToken) { + presentModifiers = getPresentModifiers(contextToken); + } + // Keep track of added missing required modifiers and modifiers already present. + // This is needed when we have overloaded signatures, + // so this callback will be called for multiple nodes/signatures, + // and we need to make sure the modifiers are uniform for all nodes/signatures. + modifiers = node.modifierFlagsCache | requiredModifiers | presentModifiers; + } + node = ts.factory.updateModifiers(node, modifiers & (~presentModifiers)); + completionNodes.push(node); + }, body, 2 /* Property */, isAbstract); + if (completionNodes.length) { + insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + } + return { insertText: insertText, isSnippet: isSnippet, importAdder: importAdder }; + } + function getPresentModifiers(contextToken) { + var modifiers = 0 /* None */; + var contextMod; + /* + Cases supported: + In + `class C { + public abstract | + }` + `contextToken` is ``abstract`` (as an identifier), + `contextToken.parent` is property declaration, + `location` is class declaration ``class C { ... }``. + In + `class C { + protected override m| + }` + `contextToken` is ``override`` (as a keyword), + `contextToken.parent` is property declaration, + `location` is identifier ``m``, + `location.parent` is property declaration ``protected override m``, + `location.parent.parent` is class declaration ``class C { ... }``. + */ + if (contextMod = isModifierLike(contextToken)) { + modifiers |= ts.modifierToFlag(contextMod); + } + if (ts.isPropertyDeclaration(contextToken.parent)) { + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + } + return modifiers; } - function originToCompletionEntryData(origin) { + function isModifierLike(node) { + if (ts.isModifier(node)) { + return node.kind; + } + if (ts.isIdentifier(node) && node.originalKeywordKind && ts.isModifierKind(node.originalKeywordKind)) { + return node.originalKeywordKind; + } + return undefined; + } + function createSnippetPrinter(printerOptions) { + var printer = ts.createPrinter(printerOptions); + var baseWriter = ts.createTextWriter(ts.getNewLineCharacter(printerOptions)); + var writer = __assign(__assign({}, baseWriter), { write: function (s) { return baseWriter.write(ts.escapeSnippetText(s)); }, nonEscapingWrite: baseWriter.write, writeLiteral: function (s) { return baseWriter.writeLiteral(ts.escapeSnippetText(s)); }, writeStringLiteral: function (s) { return baseWriter.writeStringLiteral(ts.escapeSnippetText(s)); }, writeSymbol: function (s, symbol) { return baseWriter.writeSymbol(ts.escapeSnippetText(s), symbol); }, writeParameter: function (s) { return baseWriter.writeParameter(ts.escapeSnippetText(s)); }, writeComment: function (s) { return baseWriter.writeComment(ts.escapeSnippetText(s)); }, writeProperty: function (s) { return baseWriter.writeProperty(ts.escapeSnippetText(s)); } }); return { + printSnippetList: printSnippetList, + }; + /* Snippet-escaping version of `printer.printList`. */ + function printSnippetList(format, list, sourceFile) { + writer.clear(); + printer.writeList(format, list, sourceFile, writer); + return writer.getText(); + } + } + function originToCompletionEntryData(origin) { + var ambientModuleName = origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name); + var isPackageJsonImport = origin.isFromPackageJson ? true : undefined; + if (originIsResolvedExport(origin)) { + var resolvedData = { + exportName: origin.exportName, + moduleSpecifier: origin.moduleSpecifier, + ambientModuleName: ambientModuleName, + fileName: origin.fileName, + isPackageJsonImport: isPackageJsonImport, + }; + return resolvedData; + } + var unresolvedData = { exportName: origin.exportName, + exportMapKey: origin.exportMapKey, fileName: origin.fileName, ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), isPackageJsonImport: origin.isFromPackageJson ? true : undefined, - moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, }; + return unresolvedData; + } + function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) { + var isDefaultExport = data.exportName === "default" /* Default */; + var isFromPackageJson = !!data.isPackageJsonImport; + if (completionEntryDataIsResolved(data)) { + var resolvedOrigin = { + kind: 32 /* ResolvedExport */, + exportName: data.exportName, + moduleSpecifier: data.moduleSpecifier, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return resolvedOrigin; + } + var unresolvedOrigin = { + kind: 4 /* Export */, + exportName: data.exportName, + exportMapKey: data.exportMapKey, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return unresolvedOrigin; } function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, contextToken, origin, useSemicolons, options, preferences) { var _a, _b, _c; @@ -128887,10 +129458,10 @@ var ts; var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? ts.tokenToString(151 /* TypeKeyword */) + " " : ""; var suffix = useSemicolons ? ";" : ""; switch (importKind) { - case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; - case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; - case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; - case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + ts.escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; } } function quotePropertyName(sourceFile, preferences, name) { @@ -128914,11 +129485,12 @@ var ts; return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { var _a; var start = ts.timestamp(); var variableDeclaration = getVariableDeclaration(location); var useSemicolons = ts.probablyUsesSemicolons(sourceFile); + var typeChecker = program.getTypeChecker(); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. @@ -128934,7 +129506,7 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var sortTextId = (_a = symbolToSortTextIdMap === null || symbolToSortTextIdMap === void 0 ? void 0 : symbolToSortTextIdMap[ts.getSymbolId(symbol)]) !== null && _a !== void 0 ? _a : 11 /* LocationPriority */; var sortText = (isDeprecated(symbol, typeChecker) ? 8 /* DeprecatedOffset */ + sortTextId : sortTextId).toString(); - var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); + var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind); if (!entry) { continue; } @@ -129027,11 +129599,13 @@ var ts; if (entryId.data) { var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); if (autoImport) { + var _a = getRelevantTokens(position, sourceFile), contextToken_1 = _a.contextToken, previousToken_1 = _a.previousToken; return { type: "symbol", symbol: autoImport.symbol, location: ts.getTouchingPropertyName(sourceFile, position), - previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + previousToken: previousToken_1, + contextToken: contextToken_1, isJsxInitializer: false, isTypeOnlyLocation: false, origin: autoImport.origin, @@ -129046,7 +129620,7 @@ var ts; if (completionData.kind !== 0 /* Data */) { return { type: "request", request: completionData }; } - var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, contextToken = completionData.contextToken, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; var literal = ts.find(literals, function (l) { return completionNameForLiteral(sourceFile, preferences, l) === entryId.name; }); if (literal !== undefined) return { type: "literal", literal: literal }; @@ -129057,15 +129631,15 @@ var ts; return ts.firstDefined(symbols, function (symbol, index) { var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); - return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + return info && info.name === entryId.name && (entryId.source === CompletionSource.ClassMemberSnippet && symbol.flags & 106500 /* ClassMember */ || getSourceFromOrigin(origin) === entryId.source) + ? { type: "symbol", symbol: symbol, location: location, origin: origin, contextToken: contextToken, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - var name = entryId.name; + var name = entryId.name, source = entryId.source, data = entryId.data; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); @@ -129089,8 +129663,8 @@ var ts; } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, contextToken_2 = symbolCompletion.contextToken, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken_2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -129119,21 +129693,34 @@ var ts; return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source) { if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { - var _a = getRelevantTokens(position, sourceFile), contextToken = _a.contextToken, previousToken_1 = _a.previousToken; - if (previousToken_1 && getImportStatementCompletionInfo(contextToken || previousToken_1).replacementNode) { + var _a = getRelevantTokens(position, sourceFile), contextToken_3 = _a.contextToken, previousToken_2 = _a.previousToken; + if (previousToken_2 && getImportStatementCompletionInfo(contextToken_3 || previousToken_2).replacementNode) { // Import statement completion: 'import c|' return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; } } + if (source === CompletionSource.ClassMemberSnippet) { + var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken).importAdder; + if (importAdder) { + var changes = ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, importAdder.writeFixes); + return { + sourceDisplay: undefined, + codeActions: [{ + changes: changes, + description: ts.diagnosticToString([ts.Diagnostics.Includes_imports_of_types_referenced_by_0, name]), + }], + }; + } + } if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { return { codeActions: undefined, sourceDisplay: undefined }; } var checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); var moduleSymbol = origin.moduleSymbol; - var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _b = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; + var targetSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _b = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; ts.Debug.assert(!(data === null || data === void 0 ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -129645,6 +130232,7 @@ var ts; } } function addPropertySymbol(symbol, insertAwait, insertQuestionDot) { + var _a; // For a computed property with an accessible name like `Symbol.iterator`, // we'll add a completion for the *name* `Symbol` instead of for the property. // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. @@ -129658,19 +130246,33 @@ var ts; var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + if (!moduleSymbol || + !ts.isExternalModuleSymbol(moduleSymbol) || + typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) { symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; } else { - var origin = { - kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), - moduleSymbol: moduleSymbol, - isDefaultExport: false, - symbolName: firstAccessibleSymbol.name, - exportName: firstAccessibleSymbol.name, - fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, - }; - symbolToOriginInfoMap[index] = origin; + var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; + var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + exportKind: 0 /* Named */, + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol: moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, + }], sourceFile, program, host, preferences) || {}).moduleSpecifier; + if (moduleSpecifier) { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: fileName, + moduleSpecifier: moduleSpecifier, + }; + symbolToOriginInfoMap[index] = origin; + } } } else if (preferences.includeCompletionsWithInsertText) { @@ -129827,11 +130429,11 @@ var ts; // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; - // If already using ES6 modules, OK to continue using them. + // If already using ES modules, OK to continue using them. if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + if (ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. return ts.programContainsModules(program); @@ -129906,7 +130508,7 @@ var ts; var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, preferences, !!importCompletionNode, function (context) { - exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule) { + exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule, exportMapKey) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) return; if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) @@ -129931,6 +130533,7 @@ var ts; kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, moduleSpecifier: moduleSpecifier, symbolName: symbolName, + exportMapKey: exportMapKey, exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, fileName: exportInfo_1.moduleFileName, isDefaultExport: isDefaultExport, @@ -130012,8 +130615,9 @@ var ts; function isNewIdentifierDefinitionLocation() { if (contextToken) { var containingNodeKind = contextToken.parent.kind; + var tokenKind = keywordForNode(contextToken); // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(contextToken)) { + switch (tokenKind) { case 27 /* CommaToken */: return containingNodeKind === 207 /* CallExpression */ // func( a, | || containingNodeKind === 170 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ @@ -130048,10 +130652,14 @@ var ts; return containingNodeKind === 222 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: return containingNodeKind === 232 /* TemplateSpan */; // `aa ${10} dd ${| - case 123 /* PublicKeyword */: - case 121 /* PrivateKeyword */: - case 122 /* ProtectedKeyword */: - return containingNodeKind === 166 /* PropertyDeclaration */; // class A{ public | + case 131 /* AsyncKeyword */: + return containingNodeKind === 168 /* MethodDeclaration */ // const obj = { async c|() + || containingNodeKind === 295 /* ShorthandPropertyAssignment */; // const obj = { async c| + case 41 /* AsteriskToken */: + return containingNodeKind === 168 /* MethodDeclaration */; // const obj = { * c| + } + if (isClassMemberCompletionKeyword(tokenKind)) { + return true; } } return false; @@ -130754,18 +131362,7 @@ var ts; return undefined; var isDefaultExport = data.exportName === "default" /* Default */; symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; - return { - symbol: symbol, - origin: { - kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, - moduleSymbol: moduleSymbol, - symbolName: name, - isDefaultExport: isDefaultExport, - exportName: data.exportName, - fileName: data.fileName, - isFromPackageJson: !!data.isPackageJsonImport, - } - }; + return { symbol: symbol, origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) }; } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; @@ -133146,7 +133743,7 @@ var ts; result = references; continue; } - var _loop_4 = function (entry) { + var _loop_5 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -133178,7 +133775,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_4(entry); + _loop_5(entry); } } return result; @@ -135156,7 +135753,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -135188,7 +135785,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } } function combineNormal(pathA, pathB) { @@ -136125,7 +136722,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_7 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -136137,7 +136734,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_6(sourceFile); + _loop_7(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -138141,15 +138738,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_7 = function (start) { + var _loop_8 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_2 = _loop_7(start); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(start); + if (typeof state_3 === "object") + return state_3.value; } return -1; } @@ -138812,6 +139409,7 @@ var ts; return false; } } + Rename.nodeIsEligibleForRename = nodeIsEligibleForRename; })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); /* @internal */ @@ -139527,7 +140125,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_8 = function (n) { + var _loop_9 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -139537,9 +140135,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_3 = _loop_8(n); - if (typeof state_3 === "object") - return state_3.value; + var state_4 = _loop_9(n); + if (typeof state_4 === "object") + return state_4.value; } return undefined; } @@ -140131,10 +140729,12 @@ var ts; program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; var checker = program.getTypeChecker(); - if (sourceFile.commonJsModuleIndicator && - (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + var isCommonJSFile = sourceFile.impliedNodeFormat === ts.ModuleKind.CommonJS || ts.fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]); + if (!isCommonJSFile && + sourceFile.commonJsModuleIndicator && + (ts.programContainsEsModules(program) || ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { - diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); visitedNestedConvertibleFunctions.clear(); @@ -140183,7 +140783,7 @@ var ts; } } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; - // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + // convertToEsModule only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { @@ -141110,7 +141710,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -141129,7 +141729,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -144797,7 +145397,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_10 = function (sourceFile, node) { + var _loop_11 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -144810,7 +145410,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_10(sourceFile, node); + _loop_11(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -144869,14 +145469,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_11 = function (i) { + var _loop_12 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_11(i); + _loop_12(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -144954,7 +145554,7 @@ var ts; /** Note: output node may be mutated input node. */ function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = createWriter(newLineCharacter); - var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + var newLine = ts.getNewLineKind(newLineCharacter); ts.createPrinter({ newLine: newLine, neverAsciiEscape: true, @@ -145419,21 +146019,16 @@ var ts; (function (codefix) { var errorCodeToFixes = ts.createMultiMap(); var fixIdToRegistration = new ts.Map(); - function diagnosticToString(diag) { - return ts.isArray(diag) - ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) - : ts.getLocaleSpecificMessage(diag); - } function createCodeFixActionWithoutFixAll(fixName, changes, description) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, fixAllDescription && ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { @@ -145780,7 +146375,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_12 = function (identifier) { + var _loop_13 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -145813,7 +146408,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_12(identifier); + _loop_13(identifier); } return initializers && { initializers: initializers, @@ -146104,9 +146699,6 @@ var ts; }); function makeChange(changeTracker, sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (!ts.isIdentifier(token)) { - return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.Debug.formatSyntaxKind(token.kind)); - } var param = token.parent; if (!ts.isParameter(param)) { return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.Debug.formatSyntaxKind(token.kind)); @@ -146114,9 +146706,10 @@ var ts; var i = param.parent.parameters.indexOf(param); ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.factory.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); - changeTracker.replaceNode(sourceFile, token, replacement); + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -146696,7 +147289,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 131 /* AsyncKeyword */, options); - var _loop_13 = function (returnStatement) { + var _loop_14 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -146718,9 +147311,9 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_4 = _loop_13(returnStatement); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_14(returnStatement); + if (typeof state_5 === "object") + return state_5.value; } } function getReturnStatementsWithPromiseHandlers(body, checker) { @@ -147377,11 +147970,11 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code], getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); + var moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; @@ -147390,7 +147983,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEsModule", changes, ts.Diagnostics.Convert_to_ES_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -147414,7 +148007,7 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: new ts.Set() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); @@ -147547,7 +148140,7 @@ var ts; // `const a = require("b").c` --> `import { c as a } from "./b"; return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid syntax form " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid syntax form " + name.kind); } } function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { @@ -147732,7 +148325,7 @@ var ts; case 79 /* Identifier */: return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid name kind " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid name kind " + name.kind); } } /** @@ -148052,7 +148645,11 @@ var ts; } function doChange(changes, sourceFile, _a) { var container = _a.container, typeNode = _a.typeNode, constraint = _a.constraint, name = _a.name; - changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode(/*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), /*nameType*/ undefined, /*questionToken*/ undefined, typeNode)); + changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode( + /*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), + /*nameType*/ undefined, + /*questionToken*/ undefined, typeNode, + /*members*/ undefined)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -148190,7 +148787,7 @@ var ts; var addToExisting = new ts.Map(); /** Use `getNewImportEntry` for access */ var newImports = new ts.Map(); - return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; + return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes, hasFixes: hasFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start, useAutoImportProvider); if (!info || !info.fixes.length) @@ -148341,6 +148938,9 @@ var ts; ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); } } + function hasFixes() { + return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; + } } // Sorted with the preferred fix coming first. var ImportFixKind; @@ -148360,11 +148960,11 @@ var ts; AddAsTypeOnly[AddAsTypeOnly["Required"] = 2] = "Required"; AddAsTypeOnly[AddAsTypeOnly["NotAllowed"] = 4] = "NotAllowed"; })(AddAsTypeOnly || (AddAsTypeOnly = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] - : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); + ? [getSymbolExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] + : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); var fix = ts.Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); @@ -148402,7 +149002,7 @@ var ts; } } } - function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { + function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { @@ -148415,12 +149015,12 @@ var ts; return; } var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: defaultInfo.exportKind, targetFlags: ts.skipAlias(defaultInfo.symbol, checker).flags, isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (exported.name === symbolName && checker.getMergedSymbol(ts.skipAlias(exported, checker)) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: exported, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: 0 /* Named */, targetFlags: ts.skipAlias(exported, checker).flags, isFromPackageJson: isFromPackageJson }); } } @@ -148671,12 +149271,14 @@ var ts; } var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; return fixes.reduce(function (best, fix) { + // Takes true branch of conditional if `fix` is better than `best` return compareModuleSpecifiers(fix, best, sourceFile, program, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; }); } + /** @returns `Comparison.LessThan` if `a` is better than `b`. */ function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { - return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + return ts.compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } @@ -148773,9 +149375,12 @@ var ts; })); return { fixes: fixes, symbolName: symbolName }; } + function jsxModeNeedsExplicitImport(jsx) { + return jsx === 2 /* React */ || jsx === 3 /* ReactNative */; + } function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -149344,6 +149949,7 @@ var ts; ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, @@ -149762,7 +150368,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_14 = function (info) { + var _loop_15 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -149789,7 +150395,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_14(info); + _loop_15(info); } }); })); @@ -151324,7 +151930,8 @@ var ts; insertBefore = ts.findChildOfKind(containingFunction, 98 /* FunctionKeyword */, sourceFile); break; case 213 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + var kind = containingFunction.typeParameters ? 29 /* LessThanToken */ : 20 /* OpenParenToken */; + insertBefore = ts.findChildOfKind(containingFunction, kind, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -152396,7 +153003,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_15 = function (i) { + var _loop_16 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -152405,7 +153012,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_15(i); + _loop_16(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); @@ -152544,7 +153151,7 @@ var ts; 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, sourceFile, context, preferences, importAdder, addClassElement); + addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /* body */ undefined); } } } @@ -152556,10 +153163,19 @@ var ts; }; } codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; - /** - * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. - */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement) { + var PreserveOptionalFlags; + (function (PreserveOptionalFlags) { + PreserveOptionalFlags[PreserveOptionalFlags["Method"] = 1] = "Method"; + PreserveOptionalFlags[PreserveOptionalFlags["Property"] = 2] = "Property"; + PreserveOptionalFlags[PreserveOptionalFlags["All"] = 3] = "All"; + })(PreserveOptionalFlags = codefix.PreserveOptionalFlags || (codefix.PreserveOptionalFlags = {})); + /** + * `addClassElement` will not be called if we can't figure out a representation for `symbol` in `enclosingDeclaration`. + * @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional, isAmbient) { + if (preserveOptional === void 0) { preserveOptional = 3 /* All */; } + if (isAmbient === void 0) { isAmbient = false; } var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -152572,7 +153188,7 @@ var ts; var modifiers = visibilityModifier ? ts.factory.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); - var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); + var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */) || isAmbient; var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { case 165 /* PropertySignature */: @@ -152587,7 +153203,7 @@ var ts; } } addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* Property */) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 171 /* GetAccessor */: @@ -152608,14 +153224,14 @@ var ts; var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -152636,7 +153252,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1, "One declaration implies one signature"); var signature = signatures[0]; - outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : body || createStubbedMethodBody(quotePreference)); break; } for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) { @@ -152647,21 +153263,22 @@ var ts; if (!ambient) { if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(quotePreference, signature, modifiers, name, createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, body || createStubbedMethodBody(quotePreference)); } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional && !!(preserveOptional & 1 /* Method */), modifiers, quotePreference, body)); } } break; } function outputMethod(quotePreference, signature, modifiers, name, body) { - var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder); + var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional && !!(preserveOptional & 1 /* Method */), enclosingDeclaration, importAdder); if (method) addClassElement(method); } } + codefix.addNewNodeForMemberSymbol = addNewNodeForMemberSymbol; function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { var program = context.program; var checker = program.getTypeChecker(); @@ -152799,7 +153416,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -152830,7 +153447,7 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, body); } function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { if (ts.length(signatures)) { @@ -152838,10 +153455,10 @@ var ts; return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); } } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(quotePreference)); + /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { return createStubbedBody(ts.Diagnostics.Method_not_implemented.message, quotePreference); @@ -153646,7 +154263,8 @@ var ts; var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.factory.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); var mappedIntersectionType = ts.factory.createMappedTypeNode(ts.hasEffectiveReadonlyModifier(indexSignature) ? ts.factory.createModifier(144 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, - /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type); + /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type, + /*members*/ undefined); var intersectionType = ts.factory.createIntersectionTypeNode(__spreadArray(__spreadArray(__spreadArray([], ts.getAllSuperTypeNodes(container), true), [ mappedIntersectionType ], false), (otherMembers.length ? [ts.factory.createTypeLiteralNode(otherMembers)] : ts.emptyArray), true)); @@ -154322,7 +154940,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_16 = function (element) { + var _loop_17 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -154339,7 +154957,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_16(element); + _loop_17(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { @@ -156194,7 +156812,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_18 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -156234,7 +156852,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_18(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -156889,17 +157507,17 @@ var ts; deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } - var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var useEsModuleSyntax = !!oldFile.externalModuleIndicator; var quotePreference = ts.getQuotePreference(oldFile, preferences); - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEsModuleSyntax, quotePreference); if (importsFromNewFile) { ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference); - var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax); + var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference); + var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); if (imports.length && body.length) { return __spreadArray(__spreadArray(__spreadArray(__spreadArray([], prologueDirectives, true), imports, true), [ 4 /* NewLineTrivia */ @@ -156923,10 +157541,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_18 = function (sourceFile) { + var _loop_19 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_19 = function (statement) { + var _loop_20 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -156948,12 +157566,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_19(statement); + _loop_20(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_18(sourceFile); + _loop_19(sourceFile); } } function getNamespaceLikeImport(node) { @@ -157146,7 +157764,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -157171,7 +157789,7 @@ var ts; continue; var top = getTopLevelDeclarationStatement(decl); if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEs6ModuleSyntax); + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); } if (ts.hasSyntacticModifier(decl, 512 /* Default */)) { oldFileDefault = name; @@ -157181,7 +157799,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEsModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -158317,7 +158935,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -158346,7 +158964,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_20(i); + _loop_21(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -160108,6 +160726,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); + if (!ts.Rename.nodeIsEligibleForRename(node)) + return undefined; if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; return [openingElement, closingElement].map(function (node) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 0369c572911b1..08ae00374eb91 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -973,6 +973,8 @@ declare namespace ts { readonly nameType?: TypeNode; readonly questionToken?: QuestionToken | PlusToken | MinusToken; readonly type?: TypeNode; + /** Used only to produce grammar errors */ + readonly members?: NodeArray; } export interface LiteralTypeNode extends TypeNode { readonly kind: SyntaxKind.LiteralType; @@ -3420,8 +3422,8 @@ declare namespace ts { updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; - updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode; + createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; + updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode; @@ -4040,6 +4042,7 @@ declare namespace ts { readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; + readonly includeCompletionsWithClassMemberSnippets?: boolean; readonly allowIncompleteCompletions?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -6367,23 +6370,28 @@ declare namespace ts { isIncomplete?: true; entries: CompletionEntry[]; } - interface CompletionEntryData { - /** The file name declaring the export's module symbol, if it was an external module */ - fileName?: string; - /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ - ambientModuleName?: string; - /** True if the export was found in the package.json AutoImportProvider */ - isPackageJsonImport?: true; + interface CompletionEntryDataAutoImport { /** * The name of the property or export in the module's symbol table. Differs from the completion name * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. */ exportName: string; - /** - * Set for auto imports with eagerly resolved module specifiers. - */ moduleSpecifier?: string; + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + } + interface CompletionEntryDataUnresolved extends CompletionEntryDataAutoImport { + /** The key in the `ExportMapCache` where the completion entry's `SymbolExportInfo[]` is found */ + exportMapKey: string; + } + interface CompletionEntryDataResolved extends CompletionEntryDataAutoImport { + moduleSpecifier: string; } + type CompletionEntryData = CompletionEntryDataUnresolved | CompletionEntryDataResolved; interface CompletionEntry { name: string; kind: ScriptElementKind; @@ -6973,9 +6981,9 @@ declare namespace ts { /** @deprecated Use `factory.updateIndexedAccessTypeNode` or the factory supplied by your transformation context instead. */ const updateIndexedAccessTypeNode: (node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) => IndexedAccessTypeNode; /** @deprecated Use `factory.createMappedTypeNode` or the factory supplied by your transformation context instead. */ - const createMappedTypeNode: (readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined) => MappedTypeNode; + const createMappedTypeNode: (readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined) => MappedTypeNode; /** @deprecated Use `factory.updateMappedTypeNode` or the factory supplied by your transformation context instead. */ - const updateMappedTypeNode: (node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined) => MappedTypeNode; + const updateMappedTypeNode: (node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined) => MappedTypeNode; /** @deprecated Use `factory.createLiteralTypeNode` or the factory supplied by your transformation context instead. */ const createLiteralTypeNode: (literal: LiteralExpression | BooleanLiteral | PrefixUnaryExpression | NullLiteral) => LiteralTypeNode; /** @deprecated Use `factory.updateLiteralTypeNode` or the factory supplied by your transformation context instead. */ diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index aaca3f6d45b92..83e1c8ae85997 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -21,7 +21,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -294,7 +294,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.5.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -323,21 +323,24 @@ var ts; return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; - })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { + })(NativeCollections || (NativeCollections = {})); + /* @internal */ + ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); + /* @internal */ + ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); + /* @internal */ function getCollectionImplementation(name, nativeFactory, shimFactory) { var _a; // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it. - var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator); + var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); if (constructor) return constructor; throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation."); } - ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); - ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { function getIterator(iterable) { if (iterable) { if (isArray(iterable)) @@ -2742,6 +2745,10 @@ var ts; return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } Debug.formatSyntaxKind = formatSyntaxKind; + function formatSnippetKind(kind) { + return formatEnum(kind, ts.SnippetKind, /*isFlags*/ false); + } + Debug.formatSnippetKind = formatSnippetKind; function formatNodeFlags(flags) { return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true); } @@ -4658,6 +4665,13 @@ var ts; ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ + var MemberOverrideStatus; + (function (MemberOverrideStatus) { + MemberOverrideStatus[MemberOverrideStatus["Ok"] = 0] = "Ok"; + MemberOverrideStatus[MemberOverrideStatus["NeedsOverride"] = 1] = "NeedsOverride"; + MemberOverrideStatus[MemberOverrideStatus["HasInvalidOverride"] = 2] = "HasInvalidOverride"; + })(MemberOverrideStatus = ts.MemberOverrideStatus || (ts.MemberOverrideStatus = {})); + /* @internal */ var UnionReduction; (function (UnionReduction) { UnionReduction[UnionReduction["None"] = 0] = "None"; @@ -5053,8 +5067,6 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable"; - /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 468598819] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask"; @@ -5067,6 +5079,10 @@ var ts; TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["IncludesInstantiable"] = 33554432] = "IncludesInstantiable"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check @@ -5306,7 +5322,7 @@ var ts; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - // Starting with node12, node's module resolver has significant departures from tranditional cjs resolution + // Starting with node12, node's module resolver has significant departures from traditional cjs resolution // to better support ecmascript modules and their use within node - more features are still being added, so // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12` // version-anchored resolution target @@ -5639,6 +5655,15 @@ var ts; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax + /* @internal */ + var SnippetKind; + (function (SnippetKind) { + SnippetKind[SnippetKind["TabStop"] = 0] = "TabStop"; + SnippetKind[SnippetKind["Placeholder"] = 1] = "Placeholder"; + SnippetKind[SnippetKind["Choice"] = 2] = "Choice"; + SnippetKind[SnippetKind["Variable"] = 3] = "Variable"; + })(SnippetKind = ts.SnippetKind || (ts.SnippetKind = {})); var EmitFlags; (function (EmitFlags) { EmitFlags[EmitFlags["None"] = 0] = "None"; @@ -7932,7 +7957,7 @@ var ts; } } function readDirectory(path, extensions, excludes, includes, depth) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve @@ -8017,6 +8042,11 @@ var ts; } return sys; })(); + /*@internal*/ + function setSys(s) { + ts.sys = s; + } + ts.setSys = setSys; if (ts.sys && ts.sys.getEnvironmentVariable) { setCustomPollingValues(ts.sys); ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) @@ -8327,6 +8357,7 @@ var ts; Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."), Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), + _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8868,6 +8899,9 @@ var ts; Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), 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}'."), @@ -8974,6 +9008,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), 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}'."), @@ -9526,6 +9561,8 @@ var ts; If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."), + A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."), + JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."), 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_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."), @@ -9581,7 +9618,7 @@ var ts; Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."), This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), @@ -9629,6 +9666,7 @@ var ts; Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"), Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), + Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), 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_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -9643,7 +9681,7 @@ var ts; 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"), + Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"), Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), @@ -19822,6 +19860,8 @@ var ts; case ts.ModuleKind.ES2020: case ts.ModuleKind.ES2022: case ts.ModuleKind.ESNext: + case ts.ModuleKind.Node12: + case ts.ModuleKind.NodeNext: return true; default: return false; @@ -20186,7 +20226,7 @@ var ts; } ts.getRegexFromPattern = getRegexFromPattern; /** @param path directory of the tsconfig.json */ - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -20200,9 +20240,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - if (directoryExists(basePath)) { - visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); - } + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -20307,10 +20345,14 @@ var ts; var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { case ".js" /* Js */: + case ".cjs" /* Cjs */: + case ".mjs" /* Mjs */: return 1 /* JS */; case ".jsx" /* Jsx */: return 2 /* JSX */; case ".ts" /* Ts */: + case ".cts" /* Cts */: + case ".mts" /* Mts */: return 3 /* TS */; case ".tsx" /* Tsx */: return 4 /* TSX */; @@ -20929,6 +20971,10 @@ var ts; return node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; + function escapeSnippetText(text) { + return text.replace(/\$/gm, "\\$"); + } + ts.escapeSnippetText = escapeSnippetText; })(ts || (ts = {})); /* @internal */ var ts; @@ -23086,24 +23132,26 @@ var ts; : node; } // @api - function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { + function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { var node = createBaseNode(194 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; node.questionToken = questionToken; node.type = type; + node.members = members && createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api - function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) { + function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) { return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type - ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node) + || node.members !== members + ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } // @api @@ -27130,6 +27178,25 @@ var ts; } } ts.moveEmitHelpers = moveEmitHelpers; + /** + * Gets the SnippetElement of a node. + */ + /* @internal */ + function getSnippetElement(node) { + var _a; + return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement; + } + ts.getSnippetElement = getSnippetElement; + /** + * Sets the SnippetElement of a node. + */ + /* @internal */ + function setSnippetElement(node, snippet) { + var emitNode = getOrCreateEmitNode(node); + emitNode.snippetElement = snippet; + return node; + } + ts.setSnippetElement = setSnippetElement; /* @internal */ function ignoreSourceNewlines(node) { getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */; @@ -29976,7 +30043,8 @@ var ts; visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) || + visitNodes(cbNode, cbNodes, node.members); case 195 /* LiteralType */: return visitNode(cbNode, node.literal); case 196 /* NamedTupleMember */: @@ -32110,7 +32178,10 @@ var ts; case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected); case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected); case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); - case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); + case 16 /* Parameters */: + return ts.isKeyword(token()) + ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_parameter_name, ts.tokenToString(token())) + : parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected); case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected); case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected); @@ -32866,8 +32937,9 @@ var ts; } var type = parseTypeAnnotation(); parseSemicolon(); + var members = parseList(4 /* TypeMembers */, parseTypeMember); parseExpected(19 /* CloseBraceToken */); - return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos); + return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } function parseTupleElementType() { var pos = getNodePos(); @@ -36154,16 +36226,21 @@ var ts; var pos = getNodePos(); parseExpected(129 /* AssertKeyword */); var openBracePosition = scanner.getTokenPos(); - parseExpected(18 /* OpenBraceToken */); - var multiLine = scanner.hasPrecedingLineBreak(); - var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); - if (!parseExpected(19 /* CloseBraceToken */)) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { - ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + if (parseExpected(18 /* OpenBraceToken */)) { + var multiLine = scanner.hasPrecedingLineBreak(); + var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); + if (!parseExpected(19 /* CloseBraceToken */)) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { + ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + } } + return finishNode(factory.createAssertClause(elements, multiLine), pos); + } + else { + var elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false); + return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos); } - return finishNode(factory.createAssertClause(elements, multiLine), pos); } function tokenAfterImportDefinitelyProducesImportDeclaration() { return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */; @@ -37058,8 +37135,9 @@ var ts; return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); - var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */ + || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference(); var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } @@ -38148,7 +38226,7 @@ var ts; var ts; (function (ts) { /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1 /* Preserve */, "react-native": 3 /* ReactNative */, @@ -38285,6 +38363,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: "false", }, { name: "excludeDirectories", @@ -38320,11 +38399,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, + defaultValueDescription: "false", }, { name: "help", shortName: "?", - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "watch", @@ -38334,6 +38415,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, + defaultValueDescription: "false", }, { name: "preserveWatchOutput", @@ -38341,7 +38423,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "listFiles", @@ -38354,7 +38436,8 @@ var ts; name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, - description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included + description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: "false", }, { name: "listEmittedFiles", @@ -38425,7 +38508,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, - description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it + description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: "false", }, { name: "locale", @@ -38470,6 +38554,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, + defaultValueDescription: "false", }, { name: "version", @@ -38478,6 +38563,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: "false", }, { name: "init", @@ -38485,6 +38571,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: "false", }, { name: "project", @@ -38502,7 +38589,8 @@ var ts; shortName: "b", showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: "false", }, { name: "showConfig", @@ -38510,7 +38598,8 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, - description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: "false", }, { name: "listFilesOnly", @@ -38519,7 +38608,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, isCommandLineOnly: true, - description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: "false", }, // Basic ts.targetOptionDeclaration, @@ -38639,7 +38729,6 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, transpileOptionValue: undefined, - defaultValueDescription: "n/a" }, { name: "outDir", @@ -38650,7 +38739,6 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files, - defaultValueDescription: "n/a" }, { name: "rootDir", @@ -38807,6 +38895,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: "false", }, { name: "alwaysStrict", @@ -38839,7 +38928,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined + description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: "false", }, { name: "noImplicitReturns", @@ -38855,21 +38945,24 @@ var ts; affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements + description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: "false", }, { name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Include_undefined_in_index_signature_results + description: ts.Diagnostics.Include_undefined_in_index_signature_results, + defaultValueDescription: "false", }, { name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: "false", }, { name: "noPropertyAccessFromIndexSignature", @@ -38885,6 +38978,8 @@ var ts; type: new ts.Map(ts.getEntries({ node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, + node12: ts.ModuleResolutionKind.Node12, + nodenext: ts.ModuleResolutionKind.NodeNext, })), affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, @@ -38976,7 +39071,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "allowUmdGlobalAccess", @@ -39025,7 +39120,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators + description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, + defaultValueDescription: "false", }, { name: "emitDecoratorMetadata", @@ -39033,7 +39129,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files + description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: "false", }, // Advanced { @@ -39076,7 +39173,6 @@ var ts; category: ts.Diagnostics.Backwards_Compatibility, paramType: ts.Diagnostics.FILE, transpileOptionValue: undefined, - defaultValueDescription: "n/a", description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead, }, { @@ -39157,6 +39253,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: "false", }, { name: "disableSizeLimit", @@ -39171,21 +39268,24 @@ var ts; type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects + description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: "false", }, { name: "disableSolutionSearching", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing + description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: "false", }, { name: "disableReferencedProjectLoad", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript + description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: "false", }, { name: "noImplicitUseStrict", @@ -39218,7 +39318,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "declarationDir", @@ -39229,7 +39329,6 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files, - defaultValueDescription: "n/a" }, { name: "skipLibCheck", @@ -39311,6 +39410,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: "false", }, { name: "keyofStringsOnly", @@ -39358,27 +39458,31 @@ var ts; shortName: "v", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "dry", shortName: "d", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "force", shortName: "f", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", } ]; /* @internal */ @@ -39391,10 +39495,12 @@ var ts; */ name: "enableAutoDiscovery", type: "boolean", + defaultValueDescription: "false", }, { name: "enable", type: "boolean", + defaultValueDescription: "false", }, { name: "include", @@ -39415,6 +39521,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", + defaultValueDescription: "false", }, ]; /*@internal*/ @@ -42687,11 +42794,15 @@ var ts; if (!scope || !scope.packageJsonContent.exports) { return undefined; } + if (typeof scope.packageJsonContent.name !== "string") { + return undefined; + } var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry - if (scope.packageJsonContent.name !== parts[1]) { + var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } - var trailingParts = parts.slice(2); + var trailingParts = parts.slice(nameParts.length); return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : "." + ts.directorySeparator + trailingParts.join(ts.directorySeparator), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { @@ -45830,6 +45941,7 @@ var ts; case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: case 172 /* SetAccessor */: + case 169 /* ClassStaticBlockDeclaration */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -47210,6 +47322,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isPropertyAccessible: isPropertyAccessible, getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration, + getMemberOverrideModifierStatus: getMemberOverrideModifierStatus, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -47453,6 +47566,21 @@ var ts; var enumRelation = new ts.Map(); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + // Extensions suggested for path imports when module resolution is node12 or higher. + // The first element of each tuple is the extension a file has. + // The second element of each tuple is the extension that should be used in a path import. + // e.g. if we want to import file `foo.mts`, we should write `import {} from "./foo.mjs". + var suggestedExtensions = [ + [".mts", ".mjs"], + [".ts", ".js"], + [".cts", ".cjs"], + [".mjs", ".mjs"], + [".js", ".js"], + [".cjs", ".cjs"], + [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], + [".jsx", ".jsx"], + [".json", ".json"], + ]; initializeTypeChecker(); return checker; function getJsxNamespace(location) { @@ -48169,11 +48297,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, issueSuggestions) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, issueSuggestions); + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, issueSuggestions) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { var _a, _b, _c; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; @@ -48500,7 +48628,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (issueSuggestions && suggestionCount < maximumSuggestionCount) { + if (suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -48509,7 +48637,9 @@ var ts; if (suggestion) { var suggestionName = symbolToString(suggestion); var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); - var message = isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; + var message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 + : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 + : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { @@ -48954,6 +49084,10 @@ var ts; function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === ts.ModuleKind.ESNext && targetMode === ts.ModuleKind.CommonJS; } + function isOnlyImportedAsDefault(usage) { + var usageMode = getUsageModeForExpression(usage); + return usageMode === ts.ModuleKind.ESNext && ts.endsWith(usage.text, ".json" /* Json */); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { var usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== undefined) { @@ -49004,8 +49138,9 @@ var ts; exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); + var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier); - if (!exportDefaultSymbol && !hasSyntheticDefault) { + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); @@ -49019,7 +49154,7 @@ var ts; reportNonDefaultExport(moduleSymbol, node); } } - else if (hasSyntheticDefault) { + else if (hasSyntheticDefault || hasDefaultOnly) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); @@ -49144,7 +49279,7 @@ var ts; var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); - if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } @@ -49503,7 +49638,7 @@ var ts; if (name.kind === 79 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true, false)); if (!symbol) { return getMergedSymbol(symbolFromJSPrototype); } @@ -49538,21 +49673,28 @@ var ts; var namespaceName = getFullyQualifiedName(namespace); var declarationName = ts.declarationNameToString(right); var suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); - var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); - var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); - var canSuggestTypeof = containingQualifiedName && !ts.isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (suggestionForNonexistentModule) { error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + return undefined; } - else if (canSuggestTypeof) { + var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); + var canSuggestTypeof = globalObjectType // <-- can't pull on types if global types aren't initialized yet + && (meaning & 788968 /* Type */) + && containingQualifiedName + && !ts.isTypeOfExpression(containingQualifiedName.parent) + && tryGetQualifiedNameAsValue(containingQualifiedName); + if (canSuggestTypeof) { error(containingQualifiedName, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.entityNameToString(containingQualifiedName)); + return undefined; } - else if (meaning & 1920 /* Namespace */ && exportedTypeSymbol && ts.isQualifiedName(name.parent)) { - error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); - } - else { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + if (meaning & 1920 /* Namespace */ && ts.isQualifiedName(name.parent)) { + var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); + if (exportedTypeSymbol) { + error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); + return undefined; + } } + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); } return undefined; } @@ -49654,7 +49796,7 @@ var ts; : undefined; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - var _a, _b, _c, _d, _e, _f; + var _a, _b, _c, _d, _e, _f, _g; if (isForAugmentation === void 0) { isForAugmentation = false; } if (ts.startsWith(moduleReference, "@types/")) { var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -49674,7 +49816,8 @@ var ts; ((_d = ts.findAncestor(location, ts.isExportDeclaration)) === null || _d === void 0 ? void 0 : _d.moduleSpecifier) || ((_e = (ts.isModuleDeclaration(location) ? location : location.parent && ts.isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)) === null || _e === void 0 ? void 0 : _e.name) || ((_f = (ts.isLiteralImportTypeNode(location) ? location : undefined)) === null || _f === void 0 ? void 0 : _f.argument.literal); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : undefined); // TODO: GH#18217 + var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -49687,6 +49830,9 @@ var ts; if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) { error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); } + if (mode === ts.ModuleKind.ESNext && compilerOptions.resolveJsonModule && resolvedModule.extension === ".json" /* Json */) { + error(errorNode, ts.Diagnostics.JSON_imports_are_experimental_in_ES_module_mode_imports); + } } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); @@ -49737,6 +49883,10 @@ var ts; } else { var tsExtension = ts.tryExtractTSExtension(moduleReference); + var isExtensionlessRelativePathImport = ts.pathIsRelative(moduleReference) && !ts.hasExtension(moduleReference); + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var resolutionIsNode12OrNext = moduleResolutionKind === ts.ModuleResolutionKind.Node12 || + moduleResolutionKind === ts.ModuleResolutionKind.NodeNext; if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension); @@ -49756,6 +49906,19 @@ var ts; ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } + else if (mode === ts.ModuleKind.ESNext && resolutionIsNode12OrNext && isExtensionlessRelativePathImport) { + var absoluteRef_1 = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(currentSourceFile.path)); + var suggestedExt = (_g = suggestedExtensions.find(function (_a) { + var actualExt = _a[0], _importExt = _a[1]; + return host.fileExists(absoluteRef_1 + actualExt); + })) === null || _g === void 0 ? void 0 : _g[1]; + if (suggestedExt) { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + } + else { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -49825,40 +49988,50 @@ var ts; error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } - if (ts.getESModuleInterop(compilerOptions)) { - var referenceParent = referencingLocation.parent; - if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || - ts.isImportCall(referenceParent)) { - var type = getTypeOfSymbol(symbol); + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var reference = ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier; + var type = getTypeOfSymbol(symbol); + var defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); + if (defaultOnlyType) { + return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); + } + if (ts.getESModuleInterop(compilerOptions)) { 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, ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier); - // 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 = new ts.Map(symbol.members); - if (symbol.exports) - result.exports = new ts.Map(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.indexInfos); - return result; + if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); + return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } } } } return symbol; } + /** + * Create a new symbol which has the module's type less the call and construct signatures + */ + function cloneTypeAsModuleType(symbol, moduleType, referenceParent) { + 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 = new ts.Map(symbol.members); + if (symbol.exports) + result.exports = new ts.Map(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.indexInfos); + return result; + } function hasExportAssignmentSymbol(moduleSymbol) { return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } @@ -49887,8 +50060,8 @@ var ts; if (exportEquals !== moduleSymbol) { var type = getTypeOfSymbol(exportEquals); if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { - getPropertiesOfType(type).forEach(function (symbol) { - cb(symbol, symbol.escapedName); + forEachPropertyOfType(type, function (symbol, escapedName) { + cb(symbol, escapedName); }); } } @@ -50220,12 +50393,15 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + if (isNamedMember(symbol, id)) { (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } + function isNamedMember(member, escapedName) { + return !isReservedMemberName(escapedName) && symbolIsValue(member); + } function getNamedOrIndexSignatureMembers(members) { var result = getNamedMembers(members); var index = getIndexSymbolFromSymbolTable(members); @@ -51100,7 +51276,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined; var templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), context); - var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode); + var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } @@ -57058,6 +57234,16 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function forEachPropertyOfType(type, action) { + type = getReducedApparentType(type); + if (type.flags & 3670016 /* StructuredType */) { + resolveStructuredTypeMembers(type).members.forEach(function (symbol, escapedName) { + if (isNamedMember(symbol, escapedName)) { + action(symbol, escapedName); + } + }); + } + } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { var list = obj.properties; return list.some(function (property) { @@ -57994,7 +58180,7 @@ var ts; return false; switch (node.kind) { case 79 /* Identifier */: - return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; case 166 /* PropertyDeclaration */: case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: @@ -59343,6 +59529,8 @@ var ts; // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { includes |= flags & 205258751 /* IncludesMask */; + if (flags & 465829888 /* Instantiable */) + includes |= 33554432 /* IncludesInstantiable */; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { @@ -59451,7 +59639,7 @@ var ts; var _loop_16 = function () { i--; var t = types[i]; - if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) { + if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { ts.orderedRemoveItemAt(types, i); } }; @@ -59556,7 +59744,7 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + var objectFlags = (includes & 36323363 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | (includes & 2097152 /* Intersection */ ? 33554432 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } @@ -60533,12 +60721,6 @@ var ts; } return type[cache] = type; } - function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { - var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); - var checkType = type.checkType; - var extendsType = type.extendsType; - return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); - } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -60847,6 +61029,10 @@ var ts; } return result; } + function isDistributionDependent(root) { + return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || + isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType)); + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -61646,7 +61832,9 @@ var ts; return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { if (!type.declaration.nameType) { - if (isArrayType(t)) { + var constraint = void 0; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && + (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, ts.or(isArrayType, isTupleType))) { return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); } if (isGenericTupleType(t)) { @@ -63186,13 +63374,12 @@ var ts; traceUnionsOrIntersectionsTooLarge(source, target); var result = 0 /* False */; var saveErrorInfo = captureErrorCalculationState(); - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { - result = getConstituentCount(source) * getConstituentCount(target) >= 4 ? - recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags) : - structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) { + // We skip caching when source or target is a union with no more than three constituents. + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + } + else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { + result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags); } if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { @@ -63649,19 +63836,19 @@ var ts; var maybeStart = maybeCount; maybeKeys[maybeCount] = id; maybeCount++; + var saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { sourceStack[sourceDepth] = source; sourceDepth++; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) + expandingFlags |= 1 /* Source */; } if (recursionFlags & 2 /* Target */) { targetStack[targetDepth] = target; targetDepth++; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) + expandingFlags |= 2 /* Target */; } - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) - expandingFlags |= 1 /* Source */; - if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) - expandingFlags |= 2 /* Target */; var originalHandler; var propagatingVarianceFlags = 0; if (outofbandVarianceMarkerHandler) { @@ -63685,13 +63872,13 @@ var ts; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } - expandingFlags = saveExpandingFlags; if (recursionFlags & 1 /* Source */) { sourceDepth--; } if (recursionFlags & 2 /* Target */) { targetDepth--; } + expandingFlags = saveExpandingFlags; if (result) { if (result === -1 /* True */ || (sourceDepth === 0 && targetDepth === 0)) { if (result === -1 /* True */ || result === 3 /* Maybe */) { @@ -63932,7 +64119,7 @@ var ts; originalErrorInfo = undefined; } } - else if (isGenericMappedType(target)) { + else if (isGenericMappedType(target) && relation !== identityRelation) { // Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`. var keysRemapped = !!target.declaration.nameType; var templateType = getTemplateTypeFromMappedType(target); @@ -63996,32 +64183,28 @@ var ts; } } else if (target.flags & 16777216 /* Conditional */) { - var c = target; - // Check if the conditional is always true or always false but still deferred for distribution purposes - var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); - var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); - // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, - // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when - // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, - // to which `{x: string | number, y: string | number}` isn't assignable) - var distributionMapper = void 0; - var checkVar = getActualTypeVariable(c.root.checkType); - if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { - var newParam = cloneTypeParameter(checkVar); - distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); - newParam.mapper = distributionMapper; - } - // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) - var expanding = isDeeplyNestedType(target, targetStack, targetDepth); - var localResult = expanding ? 3 /* Maybe */ : undefined; - if (skipTrue || expanding || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false))) { - if (!skipFalse && !expanding) { - localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); - } - } - if (localResult) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { resetErrorInfo(saveErrorInfo); - return localResult; + return 3 /* Maybe */; + } + var c = target; + // We check for a relationship to a conditional type target only when the conditional type has no + // 'infer' positions and is not distributive or is distributive but doesn't reference the check type + // parameter in either of the result types. + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) { + // Check if the conditional is always true or always false but still deferred for distribution purposes. + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + if (result = skipTrue ? -1 /* True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false)) { + result &= skipFalse ? -1 /* True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + } } } else if (target.flags & 134217728 /* TemplateLiteral */) { @@ -64033,8 +64216,7 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_9 = inferTypesFromTemplateLiteralType(source, target); - if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* True */; } } @@ -64092,33 +64274,34 @@ var ts; } } else if (source.flags & 16777216 /* Conditional */) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { + resetErrorInfo(saveErrorInfo); + return 3 /* Maybe */; + } if (target.flags & 16777216 /* Conditional */) { - // If one of the conditionals under comparison seems to be infinitely expanding, stop comparing it - back out, try - // the constraint, and failing that, give up trying to relate the two. This is the only way we can handle recursive conditional - // types, which might expand forever. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth) && !isDeeplyNestedType(target, targetStack, targetDepth)) { - // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if - // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, - // and Y1 is related to Y2. - var sourceParams = source.root.inferTypeParameters; - var sourceExtends = source.extendsType; - var mapper = void 0; - if (sourceParams) { - // If the source has infer type parameters, we instantiate them in the context of the target - var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); - sourceExtends = instantiateType(sourceExtends, ctx.mapper); - mapper = ctx.mapper; - } - if (isTypeIdenticalTo(sourceExtends, target.extendsType) && - (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { - if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + var sourceParams = source.root.inferTypeParameters; + var sourceExtends = source.extendsType; + var mapper = void 0; + if (sourceParams) { + // If the source has infer type parameters, we instantiate them in the context of the target + var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); + sourceExtends = instantiateType(sourceExtends, ctx.mapper); + mapper = ctx.mapper; + } + if (isTypeIdenticalTo(sourceExtends, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { + if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64133,17 +64316,13 @@ var ts; } } } - // We'll repeatedly decompose source side conditionals if they're recursive - check if we've already recured on the constraint a lot and, if so, bail - // on the comparison. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth)) { - // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` - // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). - var defaultConstraint = getDefaultConstraintOfConditionalType(source); - if (defaultConstraint) { - if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` + // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64232,9 +64411,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_10) { - return result_10; + var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_9) { + return result_9; } } } @@ -64306,13 +64485,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_11; + var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { + if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); + return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); } } } @@ -65252,14 +65431,15 @@ var ts; // `type A = null extends T ? [A>] : [T]` // has expanded into `[A>>>>>]` // in such cases we need to terminate the expansion, and we do so here. - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5) { + function isDeeplyNestedType(type, stack, depth, maxDepth) { + if (maxDepth === void 0) { maxDepth = 5; } + if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; for (var i = 0; i < depth; i++) { if (getRecursionIdentity(stack[i]) === identity_1) { count++; - if (count >= 5) { + if (count >= maxDepth) { return true; } } @@ -66000,7 +66180,8 @@ var ts; (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { var newName = "arg" + param.parent.parameters.indexOf(param); - errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + var typeName = ts.declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); return; } diagnostic = declaration.dotDotDotToken ? @@ -66394,6 +66575,10 @@ var ts; inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : undefined; } + function isTypeMatchedByTemplateLiteralType(source, target) { + var inferences = inferTypesFromTemplateLiteralType(source, target); + return !!inferences && ts.every(inferences, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); }); + } function getStringLikeTypeForType(type) { return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); } @@ -67170,17 +67355,16 @@ var ts; var inferredType = void 0; var signature = context.signature; if (signature) { - var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + var inferredCovariantType_1 = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - var inferredContravariantType = getContravariantInference(inference); // If we have both co- and contra-variant inferences, we prefer the contra-variant inference - // unless the co-variant inference is a subtype and not 'never'. - inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && - isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? - inferredCovariantType : inferredContravariantType; + // unless the co-variant inference is a subtype of some contra-variant inference and not 'never'. + inferredType = inferredCovariantType_1 && !(inferredCovariantType_1.flags & 131072 /* Never */) && + ts.some(inference.contraCandidates, function (t) { return isTypeSubtypeOf(inferredCovariantType_1, t); }) ? + inferredCovariantType_1 : getContravariantInference(inference); } - else if (inferredCovariantType) { - inferredType = inferredCovariantType; + else if (inferredCovariantType_1) { + inferredType = inferredCovariantType_1; } else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -67281,8 +67465,7 @@ var ts; if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), - /*excludeGlobals*/ false, - /*issueSuggestions*/ true) || unknownSymbol; + /*excludeGlobals*/ false) || unknownSymbol; } return links.resolvedSymbol; } @@ -67299,8 +67482,11 @@ var ts; function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 79 /* Identifier */: - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + if (!ts.isThisInTypeQuery(node)) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + } + // falls through case 108 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); case 229 /* NonNullExpression */: @@ -67480,8 +67666,9 @@ var ts; // constituent types keyed by the literal types of the property by that name in each constituent type. function getKeyPropertyName(unionType) { var types = unionType.types; - // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + // We only construct maps for unions with many non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */ || + ts.countWhere(types, function (t) { return !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */)); }) < 10) { return undefined; } if (unionType.keyPropertyName === undefined) { @@ -67514,7 +67701,7 @@ var ts; var keyPropertyName = getKeyPropertyName(unionType); var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 294 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); - var propType = propNode && getTypeOfExpression(propNode.initializer); + var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } function isOrContainsMatchingReference(source, target) { @@ -67930,7 +68117,7 @@ var ts; mapType(type, mapper); } function getConstituentCount(type) { - return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; + return type.flags & 1048576 /* Union */ ? type.types.length : 1; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -69428,7 +69615,7 @@ var ts; return parent.kind === 205 /* PropertyAccessExpression */ || parent.kind === 207 /* CallExpression */ && parent.expression === node || parent.kind === 206 /* ElementAccessExpression */ && parent.expression === node && - !(isGenericTypeWithoutNullableConstraint(type) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); + !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); @@ -70749,7 +70936,7 @@ var ts; return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 294 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -71304,6 +71491,10 @@ var ts; function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { + if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) { + return links.resolvedType = errorType; + } links.resolvedType = checkExpression(node.expression); // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. // (It needs to be bound at class evaluation time.) @@ -72773,7 +72964,7 @@ var ts; if (relatedInfo) { ts.addRelatedInfo(resultDiagnostic, relatedInfo); } - addErrorOrSuggestion(!isUncheckedJS, resultDiagnostic); + addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && @@ -72846,7 +73037,19 @@ var ts; // 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 // So the table *contains* `x` but `x` isn't actually in scope. // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. - return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + if (symbol) + return symbol; + var candidates; + if (symbols === globals) { + var primitives = ts.mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], function (s) { return symbols.has((s.charAt(0).toUpperCase() + s.slice(1))) + ? createSymbol(524288 /* TypeAlias */, s) + : undefined; }); + candidates = primitives.concat(ts.arrayFrom(symbols.values())); + } + else { + candidates = ts.arrayFrom(symbols.values()); + } + return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), candidates, meaning); }); return result; } @@ -75012,11 +75215,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } } return createPromiseReturnType(node, anyType); } + function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.parent = originalSymbol; + newSymbol.nameType = getStringLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + return createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + } + function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { + var hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier); + if (hasDefaultOnly && type && !isErrorType(type)) { + var synthType = type; + if (!synthType.defaultOnlyType) { + var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_4; + } + return synthType.defaultOnlyType; + } + return undefined; + } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { var _a; if (allowSyntheticDefaultImports && type && !isErrorType(type)) { @@ -75025,14 +75250,8 @@ var ts; var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false, moduleSpecifier); if (hasSyntheticDefault) { - var memberTable = ts.createSymbolTable(); - var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); - newSymbol.parent = originalSymbol; - newSymbol.nameType = getStringLiteralType("default"); - newSymbol.target = resolveSymbol(symbol); - memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); - var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); anonymousSymbol.type = defaultContainingObject; synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; } @@ -75740,12 +75959,12 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; + var type_5 = getBaseConstraintOfType(operandType) || operandType; // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_4.flags & 3 /* AnyOrUnknown */) { + if (type_5.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */; } - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -78335,7 +78554,9 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + if (!typeParameters) + return undefined; var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -78346,7 +78567,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); + checkIndexConstraints(type, type.symbol); checkTypeForDuplicateIndexSignatures(node); checkObjectTypeForDuplicateDeclarations(node); } @@ -78441,6 +78662,7 @@ var ts; checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { + checkGrammarMappedType(node); checkSourceElement(node.typeParameter); checkSourceElement(node.nameType); checkSourceElement(node.type); @@ -78457,6 +78679,12 @@ var ts; checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); } } + function checkGrammarMappedType(node) { + var _a; + if ((_a = node.members) === null || _a === void 0 ? void 0 : _a.length) { + return grammarErrorOnNode(node.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + } function checkThisType(node) { getTypeFromThisTypeNode(node); } @@ -78834,12 +79062,12 @@ var ts; case 264 /* ImportEqualsDeclaration */: case 267 /* NamespaceImport */: case 266 /* ImportClause */: - var result_12 = 0 /* None */; + var result_11 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { - result_12 |= getDeclarationSpaces(d); + result_11 |= getDeclarationSpaces(d); }); - return result_12; + return result_11; case 253 /* VariableDeclaration */: case 202 /* BindingElement */: case 255 /* FunctionDeclaration */: @@ -81402,7 +81630,7 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type, isStaticIndex) { + function checkIndexConstraints(type, symbol, isStaticIndex) { var indexInfos = getIndexInfosOfType(type); if (indexInfos.length === 0) { return; @@ -81413,15 +81641,15 @@ var ts; checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */, /*includeNonPublic*/ true), getNonMissingTypeOfSymbol(prop)); } } - var typeDeclaration = type.symbol.valueDeclaration; + var typeDeclaration = symbol.valueDeclaration; if (typeDeclaration && ts.isClassLike(typeDeclaration)) { for (var _b = 0, _c = typeDeclaration.members; _b < _c.length; _b++) { var member = _c[_b]; // Only process instance properties with computed names here. Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. if (!ts.isStatic(member) && !hasBindableName(member)) { - var symbol = getSymbolOfNode(member); - checkIndexConstraintForProperty(type, symbol, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol)); + var symbol_3 = getSymbolOfNode(member); + checkIndexConstraintForProperty(type, symbol_3, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol_3)); } } } @@ -81708,7 +81936,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); + checkMembersForOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -81737,14 +81965,13 @@ var ts; } } if (produceDiagnostics) { - checkIndexConstraints(type); - checkIndexConstraints(staticType, /*isStaticIndex*/ true); + checkIndexConstraints(type, symbol); + checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { - var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) { var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; @@ -81756,46 +81983,71 @@ var ts; if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { - checkClassMember(param, /*memberIsParameterProperty*/ true); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, + /* memberIsParameterProperty */ true); } }); } - checkClassMember(member); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, + /* memberIsParameterProperty */ false); }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; _loop_29(member); } - function checkClassMember(member, memberIsParameterProperty) { - var hasOverride = ts.hasOverrideModifier(member); - var hasStatic = ts.isStatic(member); - var isJs = ts.isInJSFile(member); - if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { - var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); - if (!declaredProp) { - return; - } - var thisType = hasStatic ? staticType : typeWithThis; - var baseType = hasStatic ? baseStaticType : baseWithThis; - var prop = getPropertyOfType(thisType, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); - var baseClassName = typeToString(baseWithThis); - if (prop && !baseProp && hasOverride) { - var suggestion = getSuggestedSymbolForNonexistentClassMember(ts.symbolName(declaredProp), baseType); + } + /** + * @param member Existing member node to be checked. + * Note: `member` cannot be a synthetic node. + */ + function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { + if (reportErrors === void 0) { reportErrors = true; } + var declaredProp = member.name + && getSymbolAtLocation(member.name) + || getSymbolAtLocation(member); + if (!declaredProp) { + return 0 /* Ok */; + } + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, ts.hasOverrideModifier(member), ts.hasAbstractModifier(member), ts.isStatic(member), memberIsParameterProperty, ts.symbolName(declaredProp), reportErrors ? member : undefined); + } + /** + * Checks a class member declaration for either a missing or an invalid `override` modifier. + * Note: this function can be used for speculative checking, + * i.e. checking a member that does not yet exist in the program. + * An example of that would be to call this function in a completions scenario, + * when offering a method declaration as completion. + * @param errorNode The node where we should report an error, or undefined if we should not report errors. + */ + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { + var isJs = ts.isInJSFile(node); + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { + var memberEscapedName = ts.escapeLeadingUnderscores(memberName); + var thisType = memberIsStatic ? staticType : typeWithThis; + var baseType = memberIsStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, memberEscapedName); + var baseProp = getPropertyOfType(baseType, memberEscapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && memberHasOverrideModifier) { + if (errorNode) { + var suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); // Again, using symbol name: note that's different from `symbol.escapedName` suggestion ? - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } - else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { - var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); - if (hasOverride) { - return; - } - if (!baseHasAbstract) { + return 2 /* HasInvalidOverride */; + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); + if (memberHasOverrideModifier) { + return 0 /* Ok */; + } + if (!baseHasAbstract) { + if (errorNode) { var diag = memberIsParameterProperty ? isJs ? ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : @@ -81803,20 +82055,28 @@ var ts; isJs ? ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; - error(member, diag, baseClassName); + error(errorNode, diag, baseClassName); } - else if (ts.hasAbstractModifier(member) && baseHasAbstract) { - error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + return 1 /* NeedsOverride */; + } + else if (memberHasAbstractModifier && baseHasAbstract) { + if (errorNode) { + error(errorNode, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); } + return 1 /* NeedsOverride */; } } - else if (hasOverride) { + } + else if (memberHasOverrideModifier) { + if (errorNode) { var className = typeToString(type); - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } + return 2 /* HasInvalidOverride */; } + return 0 /* Ok */; } 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 @@ -81859,6 +82119,31 @@ var ts; } } } + /** + * Checks a member declaration node to see if has a missing or invalid `override` modifier. + * @param node Class-like node where the member is declared. + * @param member Member declaration node. + * Note: `member` can be a synthetic node without a parent. + */ + function getMemberOverrideModifierStatus(node, member) { + if (!member.name) { + return 0 /* Ok */; + } + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var memberHasOverrideModifier = member.parent + ? ts.hasOverrideModifier(member) + : ts.hasSyntacticModifier(member, 16384 /* Override */); + var memberName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name)); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, ts.hasAbstractModifier(member), ts.isStatic(member), + /* memberIsParameterProperty */ false, memberName); + } function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -82129,7 +82414,7 @@ var ts; var baseType = _a[_i]; checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); } - checkIndexConstraints(type); + checkIndexConstraints(type, symbol); } } checkObjectTypeForDuplicateDeclarations(node); @@ -86320,6 +86605,9 @@ var ts; } } function checkGrammarProperty(node) { + if (ts.isComputedPropertyName(node.name) && ts.isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101 /* InKeyword */) { + return grammarErrorOnNode(node.parent.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } if (ts.isClassLike(node.parent)) { if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); @@ -86339,7 +86627,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 181 /* TypeLiteral */) { + else if (ts.isTypeLiteralNode(node.parent)) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -87016,7 +87304,7 @@ var ts; return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); case 194 /* MappedType */: ts.Debug.type(node); - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 195 /* LiteralType */: ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); @@ -94852,11 +95140,11 @@ var ts; currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } - function getJsxFactoryCalleePrimitive(childrenLength) { - return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx"; + function getJsxFactoryCalleePrimitive(isStaticChildren) { + return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx"; } - function getJsxFactoryCallee(childrenLength) { - var type = getJsxFactoryCalleePrimitive(childrenLength); + function getJsxFactoryCallee(isStaticChildren) { + var type = getJsxFactoryCalleePrimitive(isStaticChildren); return getImplicitImportForName(type); } function getImplicitJsxFragmentReference() { @@ -95003,60 +95291,37 @@ var ts; return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node); } function convertJsxChildrenToChildrenPropObject(children) { + var prop = convertJsxChildrenToChildrenPropAssignment(children); + return prop && factory.createObjectLiteralExpression([prop]); + } + function convertJsxChildrenToChildrenPropAssignment(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); - if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) - ]); + if (ts.length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) { + var result_12 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_12 && factory.createPropertyAssignment("children", result_12); } var result = ts.mapDefined(children, transformJsxChildToExpression); - return !result.length ? undefined : factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) - ]); + return ts.length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined; } function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; + var childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined; var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; }); var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties; - var segments = []; - if (attrs.length) { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - } - if (children && children.length) { - var result = convertJsxChildrenToChildrenPropObject(children); - if (result) { - segments.push(result); - } - } - if (segments.length === 0) { - objectProperties = factory.createObjectLiteralExpression([]); - // When there are no attributes, React wants {} - } - else { - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments); - } - return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location); + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : + factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : ts.emptyArray); // When there are no attributes, React wants {} + return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || ts.emptyArray, isChild, location); } - function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) { + function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { + var _a; + var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); + var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; if (compilerOptions.jsx === 5 /* ReactJSXDev */) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { // isStaticChildren development flag - args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse()); + args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); // __source development flag var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos); args.push(factory.createObjectLiteralExpression([ @@ -95068,7 +95333,7 @@ var ts; args.push(factory.createThis()); } } - var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location); + var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args), location); if (isChild) { ts.startOnNewLine(element); } @@ -95076,38 +95341,9 @@ var ts; } function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; var attrs = node.attributes.properties; - if (attrs.length === 0) { - objectProperties = factory.createNull(); - // When there are no attributes, React wants "null" - } - else { - var target = ts.getEmitScriptTarget(compilerOptions); - if (target && target >= 5 /* ES2018 */) { - objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { - return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); - }))); - } - else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); - } - } - } + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs) : + factory.createNull(); // When there are no attributes, React wants "null" var callee = currentFileState.importSpecifier === undefined ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 node) @@ -95127,7 +95363,7 @@ var ts; } } return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), - /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location); + /*keyAttr*/ undefined, children, isChild, location); } function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 @@ -95140,6 +95376,36 @@ var ts; function transformJsxSpreadAttributeToSpreadAssignment(node) { return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); } + function transformJsxAttributesToObjectProps(attrs, children) { + var target = ts.getEmitScriptTarget(compilerOptions); + return target && target >= 5 /* ES2018 */ ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : + transformJsxAttributesToExpression(attrs, children); + } + function transformJsxAttributesToProps(attrs, children) { + var props = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return ts.map(attrs, function (attr) { return isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr); }); + })); + if (children) { + props.push(children); + } + return props; + } + function transformJsxAttributesToExpression(attrs, children) { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var expressions = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + expressions.unshift(factory.createObjectLiteralExpression()); + } + if (children) { + expressions.push(factory.createObjectLiteralExpression([children])); + } + return ts.singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -98555,78 +98821,17 @@ var ts; * @param node A TemplateExpression node. */ function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - // createAdd will check if each expression binds less closely than binary '+'. - // If it does, it wraps the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var expression = ts.reduceLeft(expressions, factory.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - /** - * Gets a value indicating whether we need to include the head of a TemplateExpression. - * - * @param node A TemplateExpression node. - */ - function shouldAddTemplateHead(node) { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - /** - * Adds the head of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(factory.createStringLiteral(node.head.text)); - } - /** - * Visits and adds the template spans of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateSpans(expressions, node) { + var expression = factory.createStringLiteral(node.head.text); for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { var span = _a[_i]; - expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span.literal.text.length !== 0) { - expressions.push(factory.createStringLiteral(span.literal.text)); + var args = [ts.visitNode(span.expression, visitor, ts.isExpression)]; + if (span.literal.text.length > 0) { + args.push(factory.createStringLiteral(span.literal.text)); } + expression = factory.createCallExpression(factory.createPropertyAccessExpression(expression, "concat"), + /*typeArguments*/ undefined, args); } + return ts.setTextRange(expression, node); } /** * Visits the `super` keyword @@ -108246,7 +108451,14 @@ var ts; // clear the parenthesizer rule as we ascend currentParenthesizerRule = undefined; } - function pipelineEmitWithHintWorker(hint, node) { + function pipelineEmitWithHintWorker(hint, node, allowSnippets) { + if (allowSnippets === void 0) { allowSnippets = true; } + if (allowSnippets) { + var snippet = ts.getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -108855,6 +109067,28 @@ var ts; } } // + // Snippet Elements + // + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1 /* Placeholder */: + emitPlaceholder(hint, node, snippet); + break; + case 0 /* TabStop */: + emitTabStop(snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite("${" + snippet.order + ":"); // `${2:` + pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...` + nonEscapingWrite("}"); // `}` + // `${2:...}` + } + function emitTabStop(snippet) { + nonEscapingWrite("$" + snippet.order); + } + // // Identifiers // function emitIdentifier(node) { @@ -111093,6 +111327,15 @@ var ts; function writeProperty(s) { writer.writeProperty(s); } + function nonEscapingWrite(s) { + // This should be defined in a snippet-escaping text writer. + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } + else { + writer.write(s); + } + } function writeLine(count) { if (count === void 0) { count = 1; } for (var i = 0; i < count; i++) { @@ -112362,7 +112605,7 @@ var ts; var rootResult = tryReadDirectory(rootDir, rootDirPath); var rootSymLinkResult; if (rootResult !== undefined) { - return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -113334,7 +113577,7 @@ var ts; break; case ts.FileIncludeKind.TypeReferenceDirective: (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end); - packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), getModeForResolutionAtIndex(file, index))) === null || _g === void 0 ? void 0 : _g.packageId; + packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId; break; case ts.FileIncludeKind.LibReferenceDirective: (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end); @@ -113896,15 +114139,15 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_13 = []; var i = 0; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i)); i++; - result_14.push(resolvedModule); + result_13.push(resolvedModule); } - return result_14; + return result_13; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -114196,8 +114439,8 @@ var ts; var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); }); var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile); // ensure that types resolutions are still correct - var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); - if (typeReferenceEesolutionsChanged) { + var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); + if (typeReferenceResolutionsChanged) { structureIsReused = 1 /* SafeModules */; newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions); } @@ -115485,6 +115728,21 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { + var isNightly = ts.stringContains(ts.version, "-dev"); + if (!isNightly) { + if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); + } + else if (ts.getEmitModuleKind(options) === ts.ModuleKind.NodeNext) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext"); + } + } if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } @@ -115633,7 +115891,9 @@ var ts; } } if (options.resolveJsonModule) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } // Any emit other than common js, amd, es2015 or esnext is error @@ -115961,8 +116221,8 @@ var ts; function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + function createOptionValueDiagnostic(option1, message, arg0, arg1) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1); } function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); @@ -118206,6 +118466,9 @@ var ts; else { resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile); perDirectoryResolution.set(name, mode, resolution); + if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { + resolutionHost.onDiscoveredSymlink(); + } } resolutionsInFile.set(name, mode, resolution); watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); @@ -118674,6 +118937,11 @@ var ts; } } ts.createResolutionCache = createResolutionCache; + function resolutionIsSymlink(resolution) { + var _a, _b; + return !!(((_a = resolution.resolvedModule) === null || _a === void 0 ? void 0 : _a.originalPath) || + ((_b = resolution.resolvedTypeReferenceDirective) === null || _b === void 0 ? void 0 : _b.originalPath)); + } })(ts || (ts = {})); // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ @@ -118966,9 +119234,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_14 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_14) + return result_14; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -118988,10 +119256,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_15 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_15) + return result_15; } }); }); @@ -119284,13 +119552,15 @@ var ts; if (host.fileExists(packageJsonPath)) { var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); // TODO: Inject `require` or `import` condition based on the intended import mode - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; - if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; - return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); - } - if (packageJsonContent.exports) { - return { moduleFileToTry: path, blockedByExports: true }; + if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + if (fromExports) { + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); + } + if (packageJsonContent.exports) { + return { moduleFileToTry: path, blockedByExports: true }; + } } var versionPaths = packageJsonContent.typesVersions ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -120332,6 +120602,9 @@ var ts; sourceFilesCache.set(path, false); } } + if (sourceFile) { + sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); + } return sourceFile; } return hostSourceFile.sourceFile; @@ -121288,11 +121561,11 @@ var ts; (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [state.host.realpath ? toPath(state, state.host.realpath(path)) : path, data]; - })); if (state.watch) { + state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { + var path = _a[0], data = _a[1]; + return [state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data]; + })); state.builderPrograms.set(projectPath, program); } step++; @@ -124072,28 +124345,85 @@ var ts; /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { var current = sourceFile; - outer: while (true) { + var foundToken; + var _loop_1 = function () { // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { - var child = _a[_i]; - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); + var children = current.getChildren(sourceFile); + var i = ts.binarySearchKey(children, position, function (_, i) { return i; }, function (middle, _) { + // This last callback is more of a selector than a comparator - + // `EqualTo` causes the `middle` result to be returned + // `GreaterThan` causes recursion on the left of the middle + // `LessThan` causes recursion on the right of the middle + // Let's say you have 3 nodes, spanning positons + // pos: 1, end: 3 + // pos: 3, end: 3 + // pos: 3, end: 5 + // and you're looking for the token at positon 3 - all 3 of these nodes are overlapping with position 3. + // In fact, there's a _good argument_ that node 2 shouldn't even be allowed to exist - depending on if + // the start or end of the ranges are considered inclusive, it's either wholly subsumed by the first or the last node. + // Unfortunately, such nodes do exist. :( - See fourslash/completionsImport_tsx.tsx - empty jsx attributes create + // a zero-length node. + // What also you may not expect is that which node we return depends on the includePrecedingTokenAtEndPosition flag. + // Specifically, if includePrecedingTokenAtEndPosition is set, we return the 1-3 node, while if it's unset, we + // return the 3-5 node. (The zero length node is never correct.) This is because the includePrecedingTokenAtEndPosition + // flag causes us to return the first node whose end position matches the position and which produces and acceptable token + // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the + // position and whose end is greater than the position. + var start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { - // If this child begins after position, then all subsequent children will as well. - break; - } - var end = child.getEnd(); - if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { - current = child; - continue outer; + return 1 /* GreaterThan */; } - else if (includePrecedingTokenAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { - return previousToken; + // first element whose start position is before the input and whose end position is after or equal to the input + if (nodeContainsPosition(children[middle])) { + if (children[middle - 1]) { + // we want the _first_ element that contains the position, so left-recur if the prior node also contains the position + if (nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } } + return 0 /* EqualTo */; + } + // this complex condition makes us left-recur around a zero-length node when includePrecedingTokenAtEndPosition is set, rather than right-recur on it + if (includePrecedingTokenAtEndPosition && start === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; } + return -1 /* LessThan */; + }); + if (foundToken) { + return { value: foundToken }; } - return current; + if (i >= 0 && children[i]) { + current = children[i]; + return "continue-outer"; + } + return { value: current }; + }; + outer: while (true) { + var state_1 = _loop_1(); + if (typeof state_1 === "object") + return state_1.value; + switch (state_1) { + case "continue-outer": continue outer; + } + } + function nodeContainsPosition(node) { + var start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true); + if (start > position) { + // If this child begins after position, then all subsequent children will as well. + return false; + } + var end = node.getEnd(); + if (position < end || (position === end && (node.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { + return true; + } + else if (includePrecedingTokenAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, node); + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { + foundToken = previousToken; + return true; + } + } + return false; } } /** @@ -124736,14 +125066,14 @@ var ts; return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); } ts.programContainsModules = programContainsModules; - function programContainsEs6Modules(program) { + function programContainsEsModules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } - ts.programContainsEs6Modules = programContainsEs6Modules; - function compilerOptionsIndicateEs6Modules(compilerOptions) { + ts.programContainsEsModules = programContainsEsModules; + function compilerOptionsIndicateEsModules(compilerOptions) { return !!compilerOptions.module || ts.getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ || !!compilerOptions.noEmit; } - ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + ts.compilerOptionsIndicateEsModules = compilerOptionsIndicateEsModules; function createModuleSpecifierResolutionHost(program, host) { // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. @@ -125130,9 +125460,9 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.linkText); } ts.linkTextPart = linkTextPart; - function linkNamePart(name, target) { + function linkNamePart(text, target) { return { - text: ts.getTextOfNode(name), + text: text, kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], target: { fileName: ts.getSourceFileOfNode(target).fileName, @@ -125157,20 +125487,41 @@ var ts; } else { var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var suffix = findLinkNameEnd(link.text); + var name = ts.getTextOfNode(link.name) + link.text.slice(0, suffix); + var text = link.text.slice(suffix); var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); if (decl) { - parts.push(linkNamePart(link.name, decl)); - if (link.text) - parts.push(linkTextPart(link.text)); + parts.push(linkNamePart(name, decl)); + if (text) + parts.push(linkTextPart(text)); } else { - parts.push(linkTextPart(ts.getTextOfNode(link.name) + " " + link.text)); + parts.push(linkTextPart(name + (suffix ? "" : " ") + text)); } } parts.push(linkPart("}")); return parts; } ts.buildLinkParts = buildLinkParts; + function findLinkNameEnd(text) { + if (text.indexOf("()") === 0) + return 2; + if (text[0] !== "<") + return 0; + var brackets = 0; + var i = 0; + while (i < text.length) { + if (text[i] === "<") + brackets++; + if (text[i] === ">") + brackets--; + i++; + if (!brackets) + return i; + } + return 0; + } var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -126035,6 +126386,16 @@ var ts; return decisionFromFile !== null && decisionFromFile !== void 0 ? decisionFromFile : program.usesUriStyleNodeCoreModules; } ts.shouldUseUriStyleNodeCoreModules = shouldUseUriStyleNodeCoreModules; + function getNewLineKind(newLineCharacter) { + return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + } + ts.getNewLineKind = getNewLineKind; + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + ts.diagnosticToString = diagnosticToString; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -126074,19 +126435,24 @@ var ts; } var isDefault = exportKind === 1 /* Default */; var namedSymbol = isDefault && ts.getLocalSymbolForExportDefault(symbol) || symbol; - // A re-export merged with an export from a module augmentation can result in `symbol` - // being an external module symbol; the name it is re-exported by will be `symbolTableKey` - // (which comes from the keys of `moduleSymbol.exports`.) - var importedName = ts.isExternalModuleSymbol(namedSymbol) + // 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`. + // 2. A re-export merged with an export from a module augmentation can result in `symbol` + // being an external module symbol; the name it is re-exported by will be `symbolTableKey` + // (which comes from the keys of `moduleSymbol.exports`.) + // 3. Otherwise, we have a default/namespace import that can be imported by any name, and + // `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to + // get a better name. + var importedName = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) ? ts.unescapeLeadingUnderscores(symbolTableKey) : ts.getNameForExportedSymbol(namedSymbol, scriptTarget); var moduleName = ts.stripQuotes(moduleSymbol.name); var id = exportInfoId++; + var target = ts.skipAlias(symbol, checker); var storedSymbol = symbol.flags & 33554432 /* Transient */ ? undefined : symbol; var storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? undefined : moduleSymbol; if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); - exportInfo.add(key(importedName, symbol, moduleName, checker), { + exportInfo.add(key(importedName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { id: id, symbolTableKey: symbolTableKey, symbolName: importedName, @@ -126094,16 +126460,16 @@ var ts; moduleFile: moduleFile, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: exportKind, - targetFlags: ts.skipAlias(symbol, checker).flags, + targetFlags: target.flags, isFromPackageJson: isFromPackageJson, symbol: storedSymbol, moduleSymbol: storedModuleSymbol, }); }, - get: function (importingFile, importedName, symbol, moduleName, checker) { + get: function (importingFile, key) { if (importingFile !== usableByFileName) return; - var result = exportInfo.get(key(importedName, symbol, moduleName, checker)); + var result = exportInfo.get(key); return result === null || result === void 0 ? void 0 : result.map(rehydrateCachedInfo); }, forEach: function (importingFile, action) { @@ -126111,7 +126477,7 @@ var ts; return; exportInfo.forEach(function (info, key) { var _a = parseKey(key), symbolName = _a.symbolName, ambientModuleName = _a.ambientModuleName; - action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName); + action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName, key); }); }, releaseSymbols: function () { @@ -126176,26 +126542,16 @@ var ts; isFromPackageJson: isFromPackageJson, }; } - function key(importedName, symbol, moduleName, checker) { - var unquoted = ts.stripQuotes(moduleName); - var moduleKey = ts.isExternalModuleNameRelative(unquoted) ? "/" : unquoted; - var target = ts.skipAlias(symbol, checker); - return importedName + "|" + createSymbolKey(target) + "|" + moduleKey; + function key(importedName, symbol, ambientModuleName, checker) { + var moduleKey = ambientModuleName || ""; + return importedName + "|" + ts.getSymbolId(ts.skipAlias(symbol, checker)) + "|" + moduleKey; } function parseKey(key) { var symbolName = key.substring(0, key.indexOf("|")); var moduleKey = key.substring(key.lastIndexOf("|") + 1); - var ambientModuleName = moduleKey === "/" ? undefined : moduleKey; + var ambientModuleName = moduleKey === "" ? undefined : moduleKey; return { symbolName: symbolName, ambientModuleName: ambientModuleName }; } - function createSymbolKey(symbol) { - var key = symbol.name; - while (symbol.parent) { - key += "," + symbol.parent.name; - symbol = symbol.parent; - } - return key; - } function fileIsGlobalOnly(file) { return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; } @@ -126205,7 +126561,7 @@ var ts; } var oldFileStatementIndex = -1; var newFileStatementIndex = -1; - var _loop_1 = function (ambientModuleName) { + var _loop_2 = function (ambientModuleName) { var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); @@ -126215,9 +126571,9 @@ var ts; }; for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { var ambientModuleName = _a[_i]; - var state_1 = _loop_1(ambientModuleName); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_2(ambientModuleName); + if (typeof state_2 === "object") + return state_2.value; } return true; } @@ -126317,7 +126673,7 @@ var ts; cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, scriptTarget, checker); } checker.forEachExportAndPropertyOfModule(moduleSymbol, function (exported, key) { - if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, exported)) { + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, key)) { cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, scriptTarget, checker); } }); @@ -127637,7 +127993,7 @@ var ts; (function (Completions) { var StringCompletions; (function (StringCompletions) { - function getStringLiteralCompletions(sourceFile, position, contextToken, checker, options, host, log, preferences) { + function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); return entries && convertPathCompletions(entries); @@ -127645,12 +128001,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, host, program, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -127660,7 +128016,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -128059,7 +128415,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_2 = function (name, kind, extension) { + var _loop_3 = function (name, kind, extension) { // 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 === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -128067,7 +128423,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_2(name, kind, extension); + _loop_3(name, kind, extension); } } } @@ -128102,7 +128458,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_3 = function (moduleName) { + var _loop_4 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -128110,7 +128466,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_3(moduleName); + _loop_4(moduleName); } } if (!foundGlobal) { @@ -128386,6 +128742,8 @@ var ts; (function (CompletionSource) { /** Completions that require `this.` insertion text */ CompletionSource["ThisProperty"] = "ThisProperty/"; + /** Auto-import that comes attached to a class member snippet */ + CompletionSource["ClassMemberSnippet"] = "ClassMemberSnippet/"; })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { @@ -128494,7 +128852,6 @@ var ts; } // If the request is a continuation of an earlier `isIncomplete` response, // we can continue it from the cached previous response. - var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var incompleteCompletionsCache = preferences.allowIncompleteCompletions ? (_a = host.getIncompleteCompletionsCache) === null || _a === void 0 ? void 0 : _a.call(host) : undefined; if (incompleteCompletionsCache && completionKind === 3 /* TriggerForIncompleteCompletions */ && previousToken && ts.isIdentifier(previousToken)) { @@ -128506,7 +128863,7 @@ var ts; else { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.clear(); } - var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, typeChecker, compilerOptions, host, log, preferences); + var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences); if (stringCompletions) { return stringCompletions; } @@ -128520,7 +128877,7 @@ var ts; } switch (completionData.kind) { case 0 /* Data */: - var response = completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); + var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences); if (response === null || response === void 0 ? void 0 : response.isIncomplete) { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.set(response); } @@ -128540,20 +128897,19 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function completionEntryDataIsResolved(data) { + return !!(data === null || data === void 0 ? void 0 : data.moduleSpecifier); + } function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken) { - var _a; var previousResponse = cache.get(); if (!previousResponse) return undefined; var lowerCaseTokenText = location.text.toLowerCase(); var exportMap = ts.getExportInfoMap(file, host, program, cancellationToken); - var checker = program.getTypeChecker(); - var autoImportProvider = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); - var autoImportProviderChecker = autoImportProvider === null || autoImportProvider === void 0 ? void 0 : autoImportProvider.getTypeChecker(); var newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, program, file, preferences, /*isForImportStatementCompletion*/ false, function (context) { var entries = ts.mapDefined(previousResponse.entries, function (entry) { - if (!entry.hasAction || !entry.source || !entry.data || entry.data.moduleSpecifier) { + if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) { // Not an auto import or already resolved; keep as is return entry; } @@ -128561,8 +128917,8 @@ var ts; // No longer matches typed characters; filter out return undefined; } - var _a = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)), symbol = _a.symbol, origin = _a.origin; - var info = exportMap.get(file.path, entry.name, symbol, origin.moduleSymbol.name, origin.isFromPackageJson ? autoImportProviderChecker : checker); + var origin = ts.Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)).origin; + var info = exportMap.get(file.path, entry.data.exportMapKey); var result = info && context.tryResolve(info, !ts.isExternalModuleNameRelative(ts.stripQuotes(origin.moduleSymbol.name))); if (!result) return entry; @@ -128618,7 +128974,7 @@ var ts; // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 79 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences) { var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; // Verify if the file is JSX language variant if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { @@ -128630,7 +128986,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); // TODO: GH#18217 } else { @@ -128638,7 +128994,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, typeChecker, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -128744,14 +129100,16 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { - var _a; + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind) { + var _a, _b; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(replacementToken); var data; var isSnippet; + var source = getSourceFromOrigin(origin); var sourceDisplay; var hasAction; + var typeChecker = program.getTypeChecker(); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -128802,12 +129160,16 @@ var ts; isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; } } - if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { - return undefined; - } - if (originIsExport(origin) || originIsResolvedExport(origin)) { - data = originToCompletionEntryData(origin); - hasAction = !importCompletionNode; + if (preferences.includeCompletionsWithClassMemberSnippets && + preferences.includeCompletionsWithInsertText && + completionKind === 3 /* MemberLike */ && + isClassLikeMemberCompletion(symbol, location)) { + var importAdder = void 0; + (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); + if (importAdder === null || importAdder === void 0 ? void 0 : importAdder.hasFixes()) { + hasAction = true; + source = CompletionSource.ClassMemberSnippet; + } } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location); if (kind === "JSX attribute" /* jsxAttribute */ && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { @@ -128819,7 +129181,7 @@ var ts; && !(type.flags & 1048576 /* Union */ && ts.find(type.types, function (type) { return !!(type.flags & 528 /* BooleanLike */); }))) { if (type.flags & 402653316 /* StringLike */ || (type.flags & 1048576 /* Union */ && ts.every(type.types, function (type) { return !!(type.flags & (402653316 /* StringLike */ | 32768 /* Undefined */)); }))) { // If is string like or undefined use quotes - insertText = escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); + insertText = ts.escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); isSnippet = true; } else { @@ -128828,12 +129190,16 @@ var ts; } } if (useBraces_1) { - insertText = escapeSnippetText(name) + "={$1}"; + insertText = ts.escapeSnippetText(name) + "={$1}"; isSnippet = true; } - if (isSnippet) { - replacementSpan = ts.createTextSpanFromNode(location, sourceFile); - } + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { + return undefined; + } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = originToCompletionEntryData(origin); + hasAction = !importCompletionNode; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but @@ -128847,7 +129213,7 @@ var ts; kind: kind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), sortText: sortText, - source: getSourceFromOrigin(origin), + source: source, hasAction: hasAction ? true : undefined, isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, @@ -128859,17 +129225,222 @@ var ts; data: data, }; } - function escapeSnippetText(text) { - return text.replace(/\$/gm, "\\$"); + function isClassLikeMemberCompletion(symbol, location) { + // TODO: support JS files. + if (ts.isInJSFile(location)) { + return false; + } + // Completion symbol must be for a class member. + var memberFlags = 106500 /* ClassMember */ + & 900095 /* EnumMemberExcludes */; + /* In + `class C { + | + }` + `location` is a class-like declaration. + In + `class C { + m| + }` + `location` is an identifier, + `location.parent` is a class element declaration, + and `location.parent.parent` is a class-like declaration. + In + `abstract class C { + abstract + abstract m| + }` + `location` is a syntax list (with modifiers as children), + and `location.parent` is a class-like declaration. + */ + return !!(symbol.flags & memberFlags) && + (ts.isClassLike(location) || + (location.parent && + location.parent.parent && + ts.isClassElement(location.parent) && + location === location.parent.name && + ts.isClassLike(location.parent.parent)) || + (location.parent && + ts.isSyntaxList(location) && + ts.isClassLike(location.parent))); + } + function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken) { + var classLikeDeclaration = ts.findAncestor(location, ts.isClassLike); + if (!classLikeDeclaration) { + return { insertText: name }; + } + var isSnippet; + var insertText = name; + var checker = program.getTypeChecker(); + var sourceFile = location.getSourceFile(); + var printer = createSnippetPrinter({ + removeComments: true, + module: options.module, + target: options.target, + omitTrailingSemicolon: false, + newLine: ts.getNewLineKind(ts.getNewLineCharacter(options, ts.maybeBind(host, host.getNewLine))), + }); + var importAdder = ts.codefix.createImportAdder(sourceFile, program, preferences, host); + var body; + if (preferences.includeCompletionsWithSnippetText) { + isSnippet = true; + // We are adding a tabstop (i.e. `$0`) in the body of the suggested member, + // if it has one, so that the cursor ends up in the body once the completion is inserted. + // Note: this assumes we won't have more than one body in the completion nodes, which should be the case. + var emptyStatement = ts.factory.createExpressionStatement(ts.factory.createIdentifier("")); + ts.setSnippetElement(emptyStatement, { kind: 0 /* TabStop */, order: 0 }); + body = ts.factory.createBlock([emptyStatement], /* multiline */ true); + } + else { + body = ts.factory.createBlock([], /* multiline */ true); + } + var modifiers = 0 /* None */; + // Whether the suggested member should be abstract. + // e.g. in `abstract class C { abstract | }`, we should offer abstract method signatures at position `|`. + // Note: We are relying on checking if the context token is `abstract`, + // since other visibility modifiers (e.g. `protected`) should come *before* `abstract`. + // However, that is not true for the e.g. `override` modifier, so this check has its limitations. + var isAbstract = contextToken && isModifierLike(contextToken) === 126 /* AbstractKeyword */; + var completionNodes = []; + ts.codefix.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { program: program, host: host }, preferences, importAdder, + // `addNewNodeForMemberSymbol` calls this callback function for each new member node + // it adds for the given member symbol. + // We store these member nodes in the `completionNodes` array. + // Note: there might be: + // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; + // - One node; + // - More than one node if the member is overloaded (e.g. a method with overload signatures). + function (node) { + var requiredModifiers = 0 /* None */; + if (isAbstract) { + requiredModifiers |= 128 /* Abstract */; + } + if (ts.isClassElement(node) + && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node) === 1 /* NeedsOverride */) { + requiredModifiers |= 16384 /* Override */; + } + var presentModifiers = 0 /* None */; + if (!completionNodes.length) { + // Omit already present modifiers from the first completion node/signature. + if (contextToken) { + presentModifiers = getPresentModifiers(contextToken); + } + // Keep track of added missing required modifiers and modifiers already present. + // This is needed when we have overloaded signatures, + // so this callback will be called for multiple nodes/signatures, + // and we need to make sure the modifiers are uniform for all nodes/signatures. + modifiers = node.modifierFlagsCache | requiredModifiers | presentModifiers; + } + node = ts.factory.updateModifiers(node, modifiers & (~presentModifiers)); + completionNodes.push(node); + }, body, 2 /* Property */, isAbstract); + if (completionNodes.length) { + insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + } + return { insertText: insertText, isSnippet: isSnippet, importAdder: importAdder }; + } + function getPresentModifiers(contextToken) { + var modifiers = 0 /* None */; + var contextMod; + /* + Cases supported: + In + `class C { + public abstract | + }` + `contextToken` is ``abstract`` (as an identifier), + `contextToken.parent` is property declaration, + `location` is class declaration ``class C { ... }``. + In + `class C { + protected override m| + }` + `contextToken` is ``override`` (as a keyword), + `contextToken.parent` is property declaration, + `location` is identifier ``m``, + `location.parent` is property declaration ``protected override m``, + `location.parent.parent` is class declaration ``class C { ... }``. + */ + if (contextMod = isModifierLike(contextToken)) { + modifiers |= ts.modifierToFlag(contextMod); + } + if (ts.isPropertyDeclaration(contextToken.parent)) { + modifiers |= ts.modifiersToFlags(contextToken.parent.modifiers); + } + return modifiers; } - function originToCompletionEntryData(origin) { + function isModifierLike(node) { + if (ts.isModifier(node)) { + return node.kind; + } + if (ts.isIdentifier(node) && node.originalKeywordKind && ts.isModifierKind(node.originalKeywordKind)) { + return node.originalKeywordKind; + } + return undefined; + } + function createSnippetPrinter(printerOptions) { + var printer = ts.createPrinter(printerOptions); + var baseWriter = ts.createTextWriter(ts.getNewLineCharacter(printerOptions)); + var writer = __assign(__assign({}, baseWriter), { write: function (s) { return baseWriter.write(ts.escapeSnippetText(s)); }, nonEscapingWrite: baseWriter.write, writeLiteral: function (s) { return baseWriter.writeLiteral(ts.escapeSnippetText(s)); }, writeStringLiteral: function (s) { return baseWriter.writeStringLiteral(ts.escapeSnippetText(s)); }, writeSymbol: function (s, symbol) { return baseWriter.writeSymbol(ts.escapeSnippetText(s), symbol); }, writeParameter: function (s) { return baseWriter.writeParameter(ts.escapeSnippetText(s)); }, writeComment: function (s) { return baseWriter.writeComment(ts.escapeSnippetText(s)); }, writeProperty: function (s) { return baseWriter.writeProperty(ts.escapeSnippetText(s)); } }); return { + printSnippetList: printSnippetList, + }; + /* Snippet-escaping version of `printer.printList`. */ + function printSnippetList(format, list, sourceFile) { + writer.clear(); + printer.writeList(format, list, sourceFile, writer); + return writer.getText(); + } + } + function originToCompletionEntryData(origin) { + var ambientModuleName = origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name); + var isPackageJsonImport = origin.isFromPackageJson ? true : undefined; + if (originIsResolvedExport(origin)) { + var resolvedData = { + exportName: origin.exportName, + moduleSpecifier: origin.moduleSpecifier, + ambientModuleName: ambientModuleName, + fileName: origin.fileName, + isPackageJsonImport: isPackageJsonImport, + }; + return resolvedData; + } + var unresolvedData = { exportName: origin.exportName, + exportMapKey: origin.exportMapKey, fileName: origin.fileName, ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), isPackageJsonImport: origin.isFromPackageJson ? true : undefined, - moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, }; + return unresolvedData; + } + function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbol) { + var isDefaultExport = data.exportName === "default" /* Default */; + var isFromPackageJson = !!data.isPackageJsonImport; + if (completionEntryDataIsResolved(data)) { + var resolvedOrigin = { + kind: 32 /* ResolvedExport */, + exportName: data.exportName, + moduleSpecifier: data.moduleSpecifier, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return resolvedOrigin; + } + var unresolvedOrigin = { + kind: 4 /* Export */, + exportName: data.exportName, + exportMapKey: data.exportMapKey, + symbolName: completionName, + fileName: data.fileName, + moduleSymbol: moduleSymbol, + isDefaultExport: isDefaultExport, + isFromPackageJson: isFromPackageJson, + }; + return unresolvedOrigin; } function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, contextToken, origin, useSemicolons, options, preferences) { var _a, _b, _c; @@ -128887,10 +129458,10 @@ var ts; var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? ts.tokenToString(151 /* TypeKeyword */) + " " : ""; var suffix = useSemicolons ? ";" : ""; switch (importKind) { - case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; - case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; - case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; - case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + ts.escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; } } function quotePropertyName(sourceFile, preferences, name) { @@ -128914,11 +129485,12 @@ var ts; return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { var _a; var start = ts.timestamp(); var variableDeclaration = getVariableDeclaration(location); var useSemicolons = ts.probablyUsesSemicolons(sourceFile); + var typeChecker = program.getTypeChecker(); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. @@ -128934,7 +129506,7 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var sortTextId = (_a = symbolToSortTextIdMap === null || symbolToSortTextIdMap === void 0 ? void 0 : symbolToSortTextIdMap[ts.getSymbolId(symbol)]) !== null && _a !== void 0 ? _a : 11 /* LocationPriority */; var sortText = (isDeprecated(symbol, typeChecker) ? 8 /* DeprecatedOffset */ + sortTextId : sortTextId).toString(); - var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); + var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind); if (!entry) { continue; } @@ -129027,11 +129599,13 @@ var ts; if (entryId.data) { var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); if (autoImport) { + var _a = getRelevantTokens(position, sourceFile), contextToken_1 = _a.contextToken, previousToken_1 = _a.previousToken; return { type: "symbol", symbol: autoImport.symbol, location: ts.getTouchingPropertyName(sourceFile, position), - previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + previousToken: previousToken_1, + contextToken: contextToken_1, isJsxInitializer: false, isTypeOnlyLocation: false, origin: autoImport.origin, @@ -129046,7 +129620,7 @@ var ts; if (completionData.kind !== 0 /* Data */) { return { type: "request", request: completionData }; } - var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, contextToken = completionData.contextToken, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; var literal = ts.find(literals, function (l) { return completionNameForLiteral(sourceFile, preferences, l) === entryId.name; }); if (literal !== undefined) return { type: "literal", literal: literal }; @@ -129057,15 +129631,15 @@ var ts; return ts.firstDefined(symbols, function (symbol, index) { var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); - return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + return info && info.name === entryId.name && (entryId.source === CompletionSource.ClassMemberSnippet && symbol.flags & 106500 /* ClassMember */ || getSourceFromOrigin(origin) === entryId.source) + ? { type: "symbol", symbol: symbol, location: location, origin: origin, contextToken: contextToken, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); - var name = entryId.name; + var name = entryId.name, source = entryId.source, data = entryId.data; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); @@ -129089,8 +129663,8 @@ var ts; } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, contextToken_2 = symbolCompletion.contextToken, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken_2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -129119,21 +129693,34 @@ var ts; return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source) { if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { - var _a = getRelevantTokens(position, sourceFile), contextToken = _a.contextToken, previousToken_1 = _a.previousToken; - if (previousToken_1 && getImportStatementCompletionInfo(contextToken || previousToken_1).replacementNode) { + var _a = getRelevantTokens(position, sourceFile), contextToken_3 = _a.contextToken, previousToken_2 = _a.previousToken; + if (previousToken_2 && getImportStatementCompletionInfo(contextToken_3 || previousToken_2).replacementNode) { // Import statement completion: 'import c|' return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; } } + if (source === CompletionSource.ClassMemberSnippet) { + var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken).importAdder; + if (importAdder) { + var changes = ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, importAdder.writeFixes); + return { + sourceDisplay: undefined, + codeActions: [{ + changes: changes, + description: ts.diagnosticToString([ts.Diagnostics.Includes_imports_of_types_referenced_by_0, name]), + }], + }; + } + } if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { return { codeActions: undefined, sourceDisplay: undefined }; } var checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); var moduleSymbol = origin.moduleSymbol; - var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _b = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; + var targetSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _b = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; ts.Debug.assert(!(data === null || data === void 0 ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -129645,6 +130232,7 @@ var ts; } } function addPropertySymbol(symbol, insertAwait, insertQuestionDot) { + var _a; // For a computed property with an accessible name like `Symbol.iterator`, // we'll add a completion for the *name* `Symbol` instead of for the property. // If this is e.g. [Symbol.iterator], add a completion for `Symbol`. @@ -129658,19 +130246,33 @@ var ts; var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + if (!moduleSymbol || + !ts.isExternalModuleSymbol(moduleSymbol) || + typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) { symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; } else { - var origin = { - kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), - moduleSymbol: moduleSymbol, - isDefaultExport: false, - symbolName: firstAccessibleSymbol.name, - exportName: firstAccessibleSymbol.name, - fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, - }; - symbolToOriginInfoMap[index] = origin; + var fileName = ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? (_a = ts.getSourceFileOfModule(moduleSymbol)) === null || _a === void 0 ? void 0 : _a.fileName : undefined; + var moduleSpecifier = (ts.codefix.getModuleSpecifierForBestExportInfo([{ + exportKind: 0 /* Named */, + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol: moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: ts.skipAlias(firstAccessibleSymbol, typeChecker).flags, + }], sourceFile, program, host, preferences) || {}).moduleSpecifier; + if (moduleSpecifier) { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: fileName, + moduleSpecifier: moduleSpecifier, + }; + symbolToOriginInfoMap[index] = origin; + } } } else if (preferences.includeCompletionsWithInsertText) { @@ -129827,11 +130429,11 @@ var ts; // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; - // If already using ES6 modules, OK to continue using them. + // If already using ES modules, OK to continue using them. if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + if (ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. return ts.programContainsModules(program); @@ -129906,7 +130508,7 @@ var ts; var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, preferences, !!importCompletionNode, function (context) { - exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule) { + exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule, exportMapKey) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) return; if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) @@ -129931,6 +130533,7 @@ var ts; kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, moduleSpecifier: moduleSpecifier, symbolName: symbolName, + exportMapKey: exportMapKey, exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, fileName: exportInfo_1.moduleFileName, isDefaultExport: isDefaultExport, @@ -130012,8 +130615,9 @@ var ts; function isNewIdentifierDefinitionLocation() { if (contextToken) { var containingNodeKind = contextToken.parent.kind; + var tokenKind = keywordForNode(contextToken); // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(contextToken)) { + switch (tokenKind) { case 27 /* CommaToken */: return containingNodeKind === 207 /* CallExpression */ // func( a, | || containingNodeKind === 170 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ @@ -130048,10 +130652,14 @@ var ts; return containingNodeKind === 222 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: return containingNodeKind === 232 /* TemplateSpan */; // `aa ${10} dd ${| - case 123 /* PublicKeyword */: - case 121 /* PrivateKeyword */: - case 122 /* ProtectedKeyword */: - return containingNodeKind === 166 /* PropertyDeclaration */; // class A{ public | + case 131 /* AsyncKeyword */: + return containingNodeKind === 168 /* MethodDeclaration */ // const obj = { async c|() + || containingNodeKind === 295 /* ShorthandPropertyAssignment */; // const obj = { async c| + case 41 /* AsteriskToken */: + return containingNodeKind === 168 /* MethodDeclaration */; // const obj = { * c| + } + if (isClassMemberCompletionKeyword(tokenKind)) { + return true; } } return false; @@ -130754,18 +131362,7 @@ var ts; return undefined; var isDefaultExport = data.exportName === "default" /* Default */; symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; - return { - symbol: symbol, - origin: { - kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, - moduleSymbol: moduleSymbol, - symbolName: name, - isDefaultExport: isDefaultExport, - exportName: data.exportName, - fileName: data.fileName, - isFromPackageJson: !!data.isPackageJsonImport, - } - }; + return { symbol: symbol, origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) }; } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; @@ -133146,7 +133743,7 @@ var ts; result = references; continue; } - var _loop_4 = function (entry) { + var _loop_5 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -133178,7 +133775,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_4(entry); + _loop_5(entry); } } return result; @@ -135156,7 +135753,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -135188,7 +135785,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } } function combineNormal(pathA, pathB) { @@ -136125,7 +136722,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_6 = function (sourceFile) { + var _loop_7 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -136137,7 +136734,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_6(sourceFile); + _loop_7(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -138141,15 +138738,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_7 = function (start) { + var _loop_8 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_2 = _loop_7(start); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(start); + if (typeof state_3 === "object") + return state_3.value; } return -1; } @@ -138812,6 +139409,7 @@ var ts; return false; } } + Rename.nodeIsEligibleForRename = nodeIsEligibleForRename; })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); /* @internal */ @@ -139527,7 +140125,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_8 = function (n) { + var _loop_9 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -139537,9 +140135,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_3 = _loop_8(n); - if (typeof state_3 === "object") - return state_3.value; + var state_4 = _loop_9(n); + if (typeof state_4 === "object") + return state_4.value; } return undefined; } @@ -140131,10 +140729,12 @@ var ts; program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; var checker = program.getTypeChecker(); - if (sourceFile.commonJsModuleIndicator && - (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + var isCommonJSFile = sourceFile.impliedNodeFormat === ts.ModuleKind.CommonJS || ts.fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]); + if (!isCommonJSFile && + sourceFile.commonJsModuleIndicator && + (ts.programContainsEsModules(program) || ts.compilerOptionsIndicateEsModules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { - diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); visitedNestedConvertibleFunctions.clear(); @@ -140183,7 +140783,7 @@ var ts; } } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; - // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + // convertToEsModule only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { @@ -141110,7 +141710,7 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_10 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -141129,7 +141729,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_10(opt); } return options; } @@ -144797,7 +145397,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_10 = function (sourceFile, node) { + var _loop_11 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -144810,7 +145410,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_10(sourceFile, node); + _loop_11(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -144869,14 +145469,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_11 = function (i) { + var _loop_12 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_11(i); + _loop_12(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -144954,7 +145554,7 @@ var ts; /** Note: output node may be mutated input node. */ function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = createWriter(newLineCharacter); - var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; + var newLine = ts.getNewLineKind(newLineCharacter); ts.createPrinter({ newLine: newLine, neverAsciiEscape: true, @@ -145419,21 +146019,16 @@ var ts; (function (codefix) { var errorCodeToFixes = ts.createMultiMap(); var fixIdToRegistration = new ts.Map(); - function diagnosticToString(diag) { - return ts.isArray(diag) - ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) - : ts.getLocaleSpecificMessage(diag); - } function createCodeFixActionWithoutFixAll(fixName, changes, description) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { - return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, fixAllDescription && ts.diagnosticToString(fixAllDescription), command); } codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { @@ -145780,7 +146375,7 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_12 = function (identifier) { + var _loop_13 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; @@ -145813,7 +146408,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_12(identifier); + _loop_13(identifier); } return initializers && { initializers: initializers, @@ -146104,9 +146699,6 @@ var ts; }); function makeChange(changeTracker, sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - if (!ts.isIdentifier(token)) { - return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.Debug.formatSyntaxKind(token.kind)); - } var param = token.parent; if (!ts.isParameter(param)) { return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.Debug.formatSyntaxKind(token.kind)); @@ -146114,9 +146706,10 @@ var ts; var i = param.parent.parameters.indexOf(param); ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var typeNode = ts.factory.createTypeReferenceNode(param.name, /*typeArguments*/ undefined); var replacement = ts.factory.createParameterDeclaration( - /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.factory.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); - changeTracker.replaceNode(sourceFile, token, replacement); + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken ? ts.factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); + changeTracker.replaceNode(sourceFile, param, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -146696,7 +147289,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 131 /* AsyncKeyword */, options); - var _loop_13 = function (returnStatement) { + var _loop_14 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ false); @@ -146718,9 +147311,9 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - var state_4 = _loop_13(returnStatement); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_14(returnStatement); + if (typeof state_5 === "object") + return state_5.value; } } function getReturnStatementsWithPromiseHandlers(body, checker) { @@ -147377,11 +147970,11 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], + errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code], getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); + var moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes, ts.getEmitScriptTarget(program.getCompilerOptions()), ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; @@ -147390,7 +147983,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEsModule", changes, ts.Diagnostics.Convert_to_ES_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -147414,7 +148007,7 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { + function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: new ts.Set() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); @@ -147547,7 +148140,7 @@ var ts; // `const a = require("b").c` --> `import { c as a } from "./b"; return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid syntax form " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid syntax form " + name.kind); } } function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { @@ -147732,7 +148325,7 @@ var ts; case 79 /* Identifier */: return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); default: - return ts.Debug.assertNever(name, "Convert to ES6 module got invalid name kind " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid name kind " + name.kind); } } /** @@ -148052,7 +148645,11 @@ var ts; } function doChange(changes, sourceFile, _a) { var container = _a.container, typeNode = _a.typeNode, constraint = _a.constraint, name = _a.name; - changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode(/*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), /*nameType*/ undefined, /*questionToken*/ undefined, typeNode)); + changes.replaceNode(sourceFile, container, ts.factory.createMappedTypeNode( + /*readonlyToken*/ undefined, ts.factory.createTypeParameterDeclaration(name, ts.factory.createTypeReferenceNode(constraint)), + /*nameType*/ undefined, + /*questionToken*/ undefined, typeNode, + /*members*/ undefined)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -148190,7 +148787,7 @@ var ts; var addToExisting = new ts.Map(); /** Use `getNewImportEntry` for access */ var newImports = new ts.Map(); - return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; + return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes, hasFixes: hasFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start, useAutoImportProvider); if (!info || !info.fixes.length) @@ -148341,6 +148938,9 @@ var ts; ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); } } + function hasFixes() { + return addToNamespace.length > 0 || importType.length > 0 || addToExisting.size > 0 || newImports.size > 0; + } } // Sorted with the preferred fix coming first. var ImportFixKind; @@ -148360,11 +148960,11 @@ var ts; AddAsTypeOnly[AddAsTypeOnly["Required"] = 2] = "Required"; AddAsTypeOnly[AddAsTypeOnly["NotAllowed"] = 4] = "NotAllowed"; })(AddAsTypeOnly || (AddAsTypeOnly = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] - : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); + ? [getSymbolExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] + : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); var fix = ts.Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); @@ -148402,7 +149002,7 @@ var ts; } } } - function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { + function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { @@ -148415,12 +149015,12 @@ var ts; return; } var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: defaultInfo.exportKind, targetFlags: ts.skipAlias(defaultInfo.symbol, checker).flags, isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (exported.name === symbolName && checker.getMergedSymbol(ts.skipAlias(exported, checker)) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: exported, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: 0 /* Named */, targetFlags: ts.skipAlias(exported, checker).flags, isFromPackageJson: isFromPackageJson }); } } @@ -148671,12 +149271,14 @@ var ts; } var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; return fixes.reduce(function (best, fix) { + // Takes true branch of conditional if `fix` is better than `best` return compareModuleSpecifiers(fix, best, sourceFile, program, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; }); } + /** @returns `Comparison.LessThan` if `a` is better than `b`. */ function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { - return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + return ts.compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } @@ -148773,9 +149375,12 @@ var ts; })); return { fixes: fixes, symbolName: symbolName }; } + function jsxModeNeedsExplicitImport(jsx) { + return jsx === 2 /* React */ || jsx === 3 /* ReactNative */; + } function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -149344,6 +149949,7 @@ var ts; ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, @@ -149762,7 +150368,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_14 = function (info) { + var _loop_15 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -149789,7 +150395,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_14(info); + _loop_15(info); } }); })); @@ -151324,7 +151930,8 @@ var ts; insertBefore = ts.findChildOfKind(containingFunction, 98 /* FunctionKeyword */, sourceFile); break; case 213 /* ArrowFunction */: - insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); + var kind = containingFunction.typeParameters ? 29 /* LessThanToken */ : 20 /* OpenParenToken */; + insertBefore = ts.findChildOfKind(containingFunction, kind, sourceFile) || ts.first(containingFunction.parameters); break; default: return; @@ -152396,7 +153003,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_15 = function (i) { + var _loop_16 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -152405,7 +153012,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_15(i); + _loop_16(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); @@ -152544,7 +153151,7 @@ var ts; 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, sourceFile, context, preferences, importAdder, addClassElement); + addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /* body */ undefined); } } } @@ -152556,10 +153163,19 @@ var ts; }; } codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; - /** - * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. - */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement) { + var PreserveOptionalFlags; + (function (PreserveOptionalFlags) { + PreserveOptionalFlags[PreserveOptionalFlags["Method"] = 1] = "Method"; + PreserveOptionalFlags[PreserveOptionalFlags["Property"] = 2] = "Property"; + PreserveOptionalFlags[PreserveOptionalFlags["All"] = 3] = "All"; + })(PreserveOptionalFlags = codefix.PreserveOptionalFlags || (codefix.PreserveOptionalFlags = {})); + /** + * `addClassElement` will not be called if we can't figure out a representation for `symbol` in `enclosingDeclaration`. + * @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub. + */ + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional, isAmbient) { + if (preserveOptional === void 0) { preserveOptional = 3 /* All */; } + if (isAmbient === void 0) { isAmbient = false; } var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; @@ -152572,7 +153188,7 @@ var ts; var modifiers = visibilityModifier ? ts.factory.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); - var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); + var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */) || isAmbient; var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { case 165 /* PropertySignature */: @@ -152587,7 +153203,7 @@ var ts; } } addClassElement(ts.factory.createPropertyDeclaration( - /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, + /*decorators*/ undefined, modifiers, name, optional && (preserveOptional & 2 /* Property */) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 171 /* GetAccessor */: @@ -152608,14 +153224,14 @@ var ts; var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { addClassElement(ts.factory.createGetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; addClassElement(ts.factory.createSetAccessorDeclaration( - /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(quotePreference))); + /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : body || createStubbedMethodBody(quotePreference))); } } break; @@ -152636,7 +153252,7 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1, "One declaration implies one signature"); var signature = signatures[0]; - outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, ambient ? undefined : body || createStubbedMethodBody(quotePreference)); break; } for (var _a = 0, signatures_1 = signatures; _a < signatures_1.length; _a++) { @@ -152647,21 +153263,22 @@ var ts; if (!ambient) { if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(quotePreference, signature, modifiers, name, createStubbedMethodBody(quotePreference)); + outputMethod(quotePreference, signature, modifiers, name, body || createStubbedMethodBody(quotePreference)); } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional && !!(preserveOptional & 1 /* Method */), modifiers, quotePreference, body)); } } break; } function outputMethod(quotePreference, signature, modifiers, name, body) { - var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder); + var method = createSignatureDeclarationFromSignature(168 /* MethodDeclaration */, context, quotePreference, signature, body, name, modifiers, optional && !!(preserveOptional & 1 /* Method */), enclosingDeclaration, importAdder); if (method) addClassElement(method); } } + codefix.addNewNodeForMemberSymbol = addNewNodeForMemberSymbol; function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { var program = context.program; var checker = program.getTypeChecker(); @@ -152799,7 +153416,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference, body) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -152830,7 +153447,7 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, body); } function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { if (ts.length(signatures)) { @@ -152838,10 +153455,10 @@ var ts; return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); } } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(quotePreference)); + /*asteriskToken*/ undefined, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { return createStubbedBody(ts.Diagnostics.Method_not_implemented.message, quotePreference); @@ -153646,7 +154263,8 @@ var ts; var parameter = ts.first(indexSignature.parameters); var mappedTypeParameter = ts.factory.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); var mappedIntersectionType = ts.factory.createMappedTypeNode(ts.hasEffectiveReadonlyModifier(indexSignature) ? ts.factory.createModifier(144 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, - /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type); + /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type, + /*members*/ undefined); var intersectionType = ts.factory.createIntersectionTypeNode(__spreadArray(__spreadArray(__spreadArray([], ts.getAllSuperTypeNodes(container), true), [ mappedIntersectionType ], false), (otherMembers.length ? [ts.factory.createTypeLiteralNode(otherMembers)] : ts.emptyArray), true)); @@ -154322,7 +154940,7 @@ var ts; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. var neededNamedImports = new ts.Set(); - var _loop_16 = function (element) { + var _loop_17 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -154339,7 +154957,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_16(element); + _loop_17(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { @@ -156194,7 +156812,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_17 = function (i) { + var _loop_18 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -156234,7 +156852,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_17(i); + _loop_18(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -156889,17 +157507,17 @@ var ts; deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } - var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var useEsModuleSyntax = !!oldFile.externalModuleIndicator; var quotePreference = ts.getQuotePreference(oldFile, preferences); - var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEsModuleSyntax, quotePreference); if (importsFromNewFile) { ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); - var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference); - var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax); + var imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference); + var body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); if (imports.length && body.length) { return __spreadArray(__spreadArray(__spreadArray(__spreadArray([], prologueDirectives, true), imports, true), [ 4 /* NewLineTrivia */ @@ -156923,10 +157541,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_18 = function (sourceFile) { + var _loop_19 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_19 = function (statement) { + var _loop_20 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -156948,12 +157566,12 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_19(statement); + _loop_20(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_18(sourceFile); + _loop_19(sourceFile); } } function getNamespaceLikeImport(node) { @@ -157146,7 +157764,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEsModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -157171,7 +157789,7 @@ var ts; continue; var top = getTopLevelDeclarationStatement(decl); if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEs6ModuleSyntax); + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); } if (ts.hasSyntacticModifier(decl, 512 /* Default */)) { oldFileDefault = name; @@ -157181,7 +157799,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEsModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -158317,7 +158935,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText, rawHeadText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], rawSubsequentText = _c[2], stringIndexes = _c[3]; @@ -158346,7 +158964,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_20(i); + _loop_21(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -160108,6 +160726,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); + if (!ts.Rename.nodeIsEligibleForRename(node)) + return undefined; if (ts.isIdentifier(node) && (ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) && ts.isIntrinsicJsxName(node.escapedText)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; return [openingElement, closingElement].map(function (node) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index aec720d25af74..63ac645e4dd6c 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -22,7 +22,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { @@ -89,7 +89,7 @@ var ts; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-beta"; + ts.version = "4.5.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -118,21 +118,24 @@ var ts; return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; - })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { + })(NativeCollections || (NativeCollections = {})); + /* @internal */ + ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); + /* @internal */ + ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); + /* @internal */ function getCollectionImplementation(name, nativeFactory, shimFactory) { var _a; // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it. - var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator); + var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); if (constructor) return constructor; throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation."); } - ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim"); - ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim"); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { function getIterator(iterable) { if (iterable) { if (isArray(iterable)) @@ -2537,6 +2540,10 @@ var ts; return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } Debug.formatSyntaxKind = formatSyntaxKind; + function formatSnippetKind(kind) { + return formatEnum(kind, ts.SnippetKind, /*isFlags*/ false); + } + Debug.formatSnippetKind = formatSnippetKind; function formatNodeFlags(flags) { return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true); } @@ -4453,6 +4460,13 @@ var ts; ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ + var MemberOverrideStatus; + (function (MemberOverrideStatus) { + MemberOverrideStatus[MemberOverrideStatus["Ok"] = 0] = "Ok"; + MemberOverrideStatus[MemberOverrideStatus["NeedsOverride"] = 1] = "NeedsOverride"; + MemberOverrideStatus[MemberOverrideStatus["HasInvalidOverride"] = 2] = "HasInvalidOverride"; + })(MemberOverrideStatus = ts.MemberOverrideStatus || (ts.MemberOverrideStatus = {})); + /* @internal */ var UnionReduction; (function (UnionReduction) { UnionReduction[UnionReduction["None"] = 0] = "None"; @@ -4848,8 +4862,6 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable"; - /* @internal */ - TypeFlags[TypeFlags["NotPrimitiveUnion"] = 468598819] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask"; @@ -4862,6 +4874,10 @@ var ts; TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["IncludesInstantiable"] = 33554432] = "IncludesInstantiable"; + /* @internal */ + TypeFlags[TypeFlags["NotPrimitiveUnion"] = 36323363] = "NotPrimitiveUnion"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check @@ -5101,7 +5117,7 @@ var ts; (function (ModuleResolutionKind) { ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; - // Starting with node12, node's module resolver has significant departures from tranditional cjs resolution + // Starting with node12, node's module resolver has significant departures from traditional cjs resolution // to better support ecmascript modules and their use within node - more features are still being added, so // we can expect it to change over time, and as such, offer both a `NodeNext` moving resolution target, and a `Node12` // version-anchored resolution target @@ -5434,6 +5450,15 @@ var ts; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); + // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax + /* @internal */ + var SnippetKind; + (function (SnippetKind) { + SnippetKind[SnippetKind["TabStop"] = 0] = "TabStop"; + SnippetKind[SnippetKind["Placeholder"] = 1] = "Placeholder"; + SnippetKind[SnippetKind["Choice"] = 2] = "Choice"; + SnippetKind[SnippetKind["Variable"] = 3] = "Variable"; + })(SnippetKind = ts.SnippetKind || (ts.SnippetKind = {})); var EmitFlags; (function (EmitFlags) { EmitFlags[EmitFlags["None"] = 0] = "None"; @@ -7727,7 +7752,7 @@ var ts; } } function readDirectory(path, extensions, excludes, includes, depth) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve @@ -7812,6 +7837,11 @@ var ts; } return sys; })(); + /*@internal*/ + function setSys(s) { + ts.sys = s; + } + ts.setSys = setSys; if (ts.sys && ts.sys.getEnvironmentVariable) { setCustomPollingValues(ts.sys); ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) @@ -8122,6 +8152,7 @@ var ts; Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."), Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), + _0_is_not_allowed_as_a_parameter_name: diag(1390, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_parameter_name_1390", "'{0}' is not allowed as a parameter name."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8663,6 +8694,9 @@ var ts; Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), + Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), + Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), 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}'."), @@ -8769,6 +8803,7 @@ var ts; This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class: diag(4121, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_4121", "This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0: diag(4122, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4122", "This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'."), This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1: diag(4123, ts.DiagnosticCategory.Error, "This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base__4123", "This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?"), + Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next: diag(4124, ts.DiagnosticCategory.Error, "Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_w_4124", "Compiler option '{0}' of value '{1}' is unstable. Use nightly TypeScript to silence this error. Try updating with 'npm install -D typescript@next'."), 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}'."), @@ -9321,6 +9356,8 @@ var ts; If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1: diag(7058, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_decl_7058", "If the '{0}' package actually exposes this module, try adding a new declaration (.d.ts) file containing `declare module '{1}';`"), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead: diag(7059, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead_7059", "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead."), This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint: diag(7060, ts.DiagnosticCategory.Error, "This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_cons_7060", "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint."), + A_mapped_type_may_not_declare_properties_or_methods: diag(7061, ts.DiagnosticCategory.Error, "A_mapped_type_may_not_declare_properties_or_methods_7061", "A mapped type may not declare properties or methods."), + JSON_imports_are_experimental_in_ES_module_mode_imports: diag(7062, ts.DiagnosticCategory.Error, "JSON_imports_are_experimental_in_ES_module_mode_imports_7062", "JSON imports are experimental in ES module mode imports."), 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_TypeScript_files: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_TypeScript_files_8002", "'import ... =' can only be used in TypeScript files."), @@ -9376,7 +9413,7 @@ var ts; Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), - File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."), + File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", "File is a CommonJS module; it may be converted to an ES module."), This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), @@ -9424,6 +9461,7 @@ var ts; Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"), Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), + Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), 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_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -9438,7 +9476,7 @@ var ts; 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"), + Convert_to_ES_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES_module_95017", "Convert to ES module"), Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), @@ -19617,6 +19655,8 @@ var ts; case ts.ModuleKind.ES2020: case ts.ModuleKind.ES2022: case ts.ModuleKind.ESNext: + case ts.ModuleKind.Node12: + case ts.ModuleKind.NodeNext: return true; default: return false; @@ -19981,7 +20021,7 @@ var ts; } ts.getRegexFromPattern = getRegexFromPattern; /** @param path directory of the tsconfig.json */ - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -19995,9 +20035,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - if (directoryExists(basePath)) { - visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); - } + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -20102,10 +20140,14 @@ var ts; var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { case ".js" /* Js */: + case ".cjs" /* Cjs */: + case ".mjs" /* Mjs */: return 1 /* JS */; case ".jsx" /* Jsx */: return 2 /* JSX */; case ".ts" /* Ts */: + case ".cts" /* Cts */: + case ".mts" /* Mts */: return 3 /* TS */; case ".tsx" /* Tsx */: return 4 /* TSX */; @@ -20724,6 +20766,10 @@ var ts; return node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; + function escapeSnippetText(text) { + return text.replace(/\$/gm, "\\$"); + } + ts.escapeSnippetText = escapeSnippetText; })(ts || (ts = {})); /* @internal */ var ts; @@ -22881,24 +22927,26 @@ var ts; : node; } // @api - function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { + function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members) { var node = createBaseNode(194 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; node.questionToken = questionToken; node.type = type; + node.members = members && createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api - function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) { + function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type, members) { return node.readonlyToken !== readonlyToken || node.typeParameter !== typeParameter || node.nameType !== nameType || node.questionToken !== questionToken || node.type !== type - ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node) + || node.members !== members + ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } // @api @@ -26925,6 +26973,25 @@ var ts; } } ts.moveEmitHelpers = moveEmitHelpers; + /** + * Gets the SnippetElement of a node. + */ + /* @internal */ + function getSnippetElement(node) { + var _a; + return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.snippetElement; + } + ts.getSnippetElement = getSnippetElement; + /** + * Sets the SnippetElement of a node. + */ + /* @internal */ + function setSnippetElement(node, snippet) { + var emitNode = getOrCreateEmitNode(node); + emitNode.snippetElement = snippet; + return node; + } + ts.setSnippetElement = setSnippetElement; /* @internal */ function ignoreSourceNewlines(node) { getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */; @@ -29771,7 +29838,8 @@ var ts; visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) || + visitNodes(cbNode, cbNodes, node.members); case 195 /* LiteralType */: return visitNode(cbNode, node.literal); case 196 /* NamedTupleMember */: @@ -31905,7 +31973,10 @@ var ts; case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected); case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected); case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); - case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); + case 16 /* Parameters */: + return ts.isKeyword(token()) + ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_parameter_name, ts.tokenToString(token())) + : parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected); case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected); case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected); case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected); @@ -32661,8 +32732,9 @@ var ts; } var type = parseTypeAnnotation(); parseSemicolon(); + var members = parseList(4 /* TypeMembers */, parseTypeMember); parseExpected(19 /* CloseBraceToken */); - return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos); + return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); } function parseTupleElementType() { var pos = getNodePos(); @@ -35949,16 +36021,21 @@ var ts; var pos = getNodePos(); parseExpected(129 /* AssertKeyword */); var openBracePosition = scanner.getTokenPos(); - parseExpected(18 /* OpenBraceToken */); - var multiLine = scanner.hasPrecedingLineBreak(); - var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); - if (!parseExpected(19 /* CloseBraceToken */)) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { - ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + if (parseExpected(18 /* OpenBraceToken */)) { + var multiLine = scanner.hasPrecedingLineBreak(); + var elements = parseDelimitedList(24 /* AssertEntries */, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true); + if (!parseExpected(19 /* CloseBraceToken */)) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { + ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + } } + return finishNode(factory.createAssertClause(elements, multiLine), pos); + } + else { + var elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false); + return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos); } - return finishNode(factory.createAssertClause(elements, multiLine), pos); } function tokenAfterImportDefinitelyProducesImportDeclaration() { return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */; @@ -36853,8 +36930,9 @@ var ts; return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); - var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var isMarkdownOrJSDocLink = token() === 22 /* OpenBracketToken */ + || lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference(); var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } @@ -37943,7 +38021,7 @@ var ts; var ts; (function (ts) { /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1 /* Preserve */, "react-native": 3 /* ReactNative */, @@ -38080,6 +38158,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: "false", }, { name: "excludeDirectories", @@ -38115,11 +38194,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, + defaultValueDescription: "false", }, { name: "help", shortName: "?", - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "watch", @@ -38129,6 +38210,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, + defaultValueDescription: "false", }, { name: "preserveWatchOutput", @@ -38136,7 +38218,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "listFiles", @@ -38149,7 +38231,8 @@ var ts; name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, - description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included + description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: "false", }, { name: "listEmittedFiles", @@ -38220,7 +38303,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, - description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it + description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: "false", }, { name: "locale", @@ -38265,6 +38349,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, + defaultValueDescription: "false", }, { name: "version", @@ -38273,6 +38358,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: "false", }, { name: "init", @@ -38280,6 +38366,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: "false", }, { name: "project", @@ -38297,7 +38384,8 @@ var ts; shortName: "b", showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: "false", }, { name: "showConfig", @@ -38305,7 +38393,8 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, - description: ts.Diagnostics.Print_the_final_configuration_instead_of_building + description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: "false", }, { name: "listFilesOnly", @@ -38314,7 +38403,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, isCommandLineOnly: true, - description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: "false", }, // Basic ts.targetOptionDeclaration, @@ -38434,7 +38524,6 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, transpileOptionValue: undefined, - defaultValueDescription: "n/a" }, { name: "outDir", @@ -38445,7 +38534,6 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Specify_an_output_folder_for_all_emitted_files, - defaultValueDescription: "n/a" }, { name: "rootDir", @@ -38602,6 +38690,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: "false", }, { name: "alwaysStrict", @@ -38634,7 +38723,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined + description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: "false", }, { name: "noImplicitReturns", @@ -38650,21 +38740,24 @@ var ts; affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements + description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: "false", }, { name: "noUncheckedIndexedAccess", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Include_undefined_in_index_signature_results + description: ts.Diagnostics.Include_undefined_in_index_signature_results, + defaultValueDescription: "false", }, { name: "noImplicitOverride", type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, - description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: "false", }, { name: "noPropertyAccessFromIndexSignature", @@ -38680,6 +38773,8 @@ var ts; type: new ts.Map(ts.getEntries({ node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, + node12: ts.ModuleResolutionKind.Node12, + nodenext: ts.ModuleResolutionKind.NodeNext, })), affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, @@ -38771,7 +38866,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "allowUmdGlobalAccess", @@ -38820,7 +38915,8 @@ var ts; type: "boolean", affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators + description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, + defaultValueDescription: "false", }, { name: "emitDecoratorMetadata", @@ -38828,7 +38924,8 @@ var ts; affectsSemanticDiagnostics: true, affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, - description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files + description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: "false", }, // Advanced { @@ -38871,7 +38968,6 @@ var ts; category: ts.Diagnostics.Backwards_Compatibility, paramType: ts.Diagnostics.FILE, transpileOptionValue: undefined, - defaultValueDescription: "n/a", description: ts.Diagnostics.Deprecated_setting_Use_outFile_instead, }, { @@ -38952,6 +39048,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: "false", }, { name: "disableSizeLimit", @@ -38966,21 +39063,24 @@ var ts; type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects + description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: "false", }, { name: "disableSolutionSearching", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing + description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: "false", }, { name: "disableReferencedProjectLoad", type: "boolean", isTSConfigOnly: true, category: ts.Diagnostics.Projects, - description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript + description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: "false", }, { name: "noImplicitUseStrict", @@ -39013,7 +39113,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "n/a" + defaultValueDescription: "false", }, { name: "declarationDir", @@ -39024,7 +39124,6 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Specify_the_output_directory_for_generated_declaration_files, - defaultValueDescription: "n/a" }, { name: "skipLibCheck", @@ -39106,6 +39205,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: "false", }, { name: "keyofStringsOnly", @@ -39153,27 +39253,31 @@ var ts; shortName: "v", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "dry", shortName: "d", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "force", shortName: "f", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" + type: "boolean", + defaultValueDescription: "false", } ]; /* @internal */ @@ -39186,10 +39290,12 @@ var ts; */ name: "enableAutoDiscovery", type: "boolean", + defaultValueDescription: "false", }, { name: "enable", type: "boolean", + defaultValueDescription: "false", }, { name: "include", @@ -39210,6 +39316,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", + defaultValueDescription: "false", }, ]; /*@internal*/ @@ -42482,11 +42589,15 @@ var ts; if (!scope || !scope.packageJsonContent.exports) { return undefined; } + if (typeof scope.packageJsonContent.name !== "string") { + return undefined; + } var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry - if (scope.packageJsonContent.name !== parts[1]) { + var nameParts = ts.getPathComponents(scope.packageJsonContent.name); + if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) { return undefined; } - var trailingParts = parts.slice(2); + var trailingParts = parts.slice(nameParts.length); return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : "." + ts.directorySeparator + trailingParts.join(ts.directorySeparator), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { @@ -45625,6 +45736,7 @@ var ts; case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: case 172 /* SetAccessor */: + case 169 /* ClassStaticBlockDeclaration */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -47005,6 +47117,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isPropertyAccessible: isPropertyAccessible, getTypeOnlyAliasDeclaration: getTypeOnlyAliasDeclaration, + getMemberOverrideModifierStatus: getMemberOverrideModifierStatus, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -47248,6 +47361,21 @@ var ts; var enumRelation = new ts.Map(); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + // Extensions suggested for path imports when module resolution is node12 or higher. + // The first element of each tuple is the extension a file has. + // The second element of each tuple is the extension that should be used in a path import. + // e.g. if we want to import file `foo.mts`, we should write `import {} from "./foo.mjs". + var suggestedExtensions = [ + [".mts", ".mjs"], + [".ts", ".js"], + [".cts", ".cjs"], + [".mjs", ".mjs"], + [".js", ".js"], + [".cjs", ".cjs"], + [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], + [".jsx", ".jsx"], + [".json", ".json"], + ]; initializeTypeChecker(); return checker; function getJsxNamespace(location) { @@ -47964,11 +48092,11 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, issueSuggestions) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, issueSuggestions); + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, issueSuggestions) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { var _a, _b, _c; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; @@ -48295,7 +48423,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (issueSuggestions && suggestionCount < maximumSuggestionCount) { + if (suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -48304,7 +48432,9 @@ var ts; if (suggestion) { var suggestionName = symbolToString(suggestion); var isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ false); - var message = isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; + var message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && ts.nodeIsSynthesized(nameArg) ? ts.Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 + : isUncheckedJS ? ts.Diagnostics.Could_not_find_name_0_Did_you_mean_1 + : ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1; var diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { @@ -48749,6 +48879,10 @@ var ts; function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === ts.ModuleKind.ESNext && targetMode === ts.ModuleKind.CommonJS; } + function isOnlyImportedAsDefault(usage) { + var usageMode = getUsageModeForExpression(usage); + return usageMode === ts.ModuleKind.ESNext && ts.endsWith(usage.text, ".json" /* Json */); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { var usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== undefined) { @@ -48799,8 +48933,9 @@ var ts; exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); + var hasDefaultOnly = isOnlyImportedAsDefault(node.parent.moduleSpecifier); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, node.parent.moduleSpecifier); - if (!exportDefaultSymbol && !hasSyntheticDefault) { + if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); @@ -48814,7 +48949,7 @@ var ts; reportNonDefaultExport(moduleSymbol, node); } } - else if (hasSyntheticDefault) { + else if (hasSyntheticDefault || hasDefaultOnly) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false); @@ -48939,7 +49074,7 @@ var ts; var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); - if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } @@ -49298,7 +49433,7 @@ var ts; if (name.kind === 79 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true, false)); if (!symbol) { return getMergedSymbol(symbolFromJSPrototype); } @@ -49333,21 +49468,28 @@ var ts; var namespaceName = getFullyQualifiedName(namespace); var declarationName = ts.declarationNameToString(right); var suggestionForNonexistentModule = getSuggestedSymbolForNonexistentModule(right, namespace); - var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); - var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); - var canSuggestTypeof = containingQualifiedName && !ts.isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (suggestionForNonexistentModule) { error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestionForNonexistentModule)); + return undefined; } - else if (canSuggestTypeof) { + var containingQualifiedName = ts.isQualifiedName(name) && getContainingQualifiedNameNode(name); + var canSuggestTypeof = globalObjectType // <-- can't pull on types if global types aren't initialized yet + && (meaning & 788968 /* Type */) + && containingQualifiedName + && !ts.isTypeOfExpression(containingQualifiedName.parent) + && tryGetQualifiedNameAsValue(containingQualifiedName); + if (canSuggestTypeof) { error(containingQualifiedName, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.entityNameToString(containingQualifiedName)); + return undefined; } - else if (meaning & 1920 /* Namespace */ && exportedTypeSymbol && ts.isQualifiedName(name.parent)) { - error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); - } - else { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); + if (meaning & 1920 /* Namespace */ && ts.isQualifiedName(name.parent)) { + var exportedTypeSymbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); + if (exportedTypeSymbol) { + error(name.parent.right, 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, symbolToString(exportedTypeSymbol), ts.unescapeLeadingUnderscores(name.parent.right.escapedText)); + return undefined; + } } + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName); } return undefined; } @@ -49449,7 +49591,7 @@ var ts; : undefined; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - var _a, _b, _c, _d, _e, _f; + var _a, _b, _c, _d, _e, _f, _g; if (isForAugmentation === void 0) { isForAugmentation = false; } if (ts.startsWith(moduleReference, "@types/")) { var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -49469,7 +49611,8 @@ var ts; ((_d = ts.findAncestor(location, ts.isExportDeclaration)) === null || _d === void 0 ? void 0 : _d.moduleSpecifier) || ((_e = (ts.isModuleDeclaration(location) ? location : location.parent && ts.isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)) === null || _e === void 0 ? void 0 : _e.name) || ((_f = (ts.isLiteralImportTypeNode(location) ? location : undefined)) === null || _f === void 0 ? void 0 : _f.argument.literal); - var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : undefined); // TODO: GH#18217 + var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -49482,6 +49625,9 @@ var ts; if (isSyncImport && sourceFile.impliedNodeFormat === ts.ModuleKind.ESNext) { error(errorNode, ts.Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead, moduleReference); } + if (mode === ts.ModuleKind.ESNext && compilerOptions.resolveJsonModule && resolvedModule.extension === ".json" /* Json */) { + error(errorNode, ts.Diagnostics.JSON_imports_are_experimental_in_ES_module_mode_imports); + } } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); @@ -49532,6 +49678,10 @@ var ts; } else { var tsExtension = ts.tryExtractTSExtension(moduleReference); + var isExtensionlessRelativePathImport = ts.pathIsRelative(moduleReference) && !ts.hasExtension(moduleReference); + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var resolutionIsNode12OrNext = moduleResolutionKind === ts.ModuleResolutionKind.Node12 || + moduleResolutionKind === ts.ModuleResolutionKind.NodeNext; if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension); @@ -49551,6 +49701,19 @@ var ts; ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } + else if (mode === ts.ModuleKind.ESNext && resolutionIsNode12OrNext && isExtensionlessRelativePathImport) { + var absoluteRef_1 = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(currentSourceFile.path)); + var suggestedExt = (_g = suggestedExtensions.find(function (_a) { + var actualExt = _a[0], _importExt = _a[1]; + return host.fileExists(absoluteRef_1 + actualExt); + })) === null || _g === void 0 ? void 0 : _g[1]; + if (suggestedExt) { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); + } + else { + error(errorNode, ts.Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path); + } + } else { error(errorNode, moduleNotFoundError, moduleReference); } @@ -49620,40 +49783,50 @@ var ts; error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } - if (ts.getESModuleInterop(compilerOptions)) { - var referenceParent = referencingLocation.parent; - if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || - ts.isImportCall(referenceParent)) { - var type = getTypeOfSymbol(symbol); + var referenceParent = referencingLocation.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var reference = ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier; + var type = getTypeOfSymbol(symbol); + var defaultOnlyType = getTypeWithSyntheticDefaultOnly(type, symbol, moduleSymbol, reference); + if (defaultOnlyType) { + return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); + } + if (ts.getESModuleInterop(compilerOptions)) { 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, ts.isImportCall(referenceParent) ? referenceParent.arguments[0] : referenceParent.moduleSpecifier); - // 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 = new ts.Map(symbol.members); - if (symbol.exports) - result.exports = new ts.Map(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.indexInfos); - return result; + if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); + return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } } } } return symbol; } + /** + * Create a new symbol which has the module's type less the call and construct signatures + */ + function cloneTypeAsModuleType(symbol, moduleType, referenceParent) { + 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 = new ts.Map(symbol.members); + if (symbol.exports) + result.exports = new ts.Map(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.indexInfos); + return result; + } function hasExportAssignmentSymbol(moduleSymbol) { return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined; } @@ -49682,8 +49855,8 @@ var ts; if (exportEquals !== moduleSymbol) { var type = getTypeOfSymbol(exportEquals); if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { - getPropertiesOfType(type).forEach(function (symbol) { - cb(symbol, symbol.escapedName); + forEachPropertyOfType(type, function (symbol, escapedName) { + cb(symbol, escapedName); }); } } @@ -50015,12 +50188,15 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + if (isNamedMember(symbol, id)) { (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } + function isNamedMember(member, escapedName) { + return !isReservedMemberName(escapedName) && symbolIsValue(member); + } function getNamedOrIndexSignatureMembers(members) { var result = getNamedMembers(members); var index = getIndexSymbolFromSymbolTable(members); @@ -50895,7 +51071,7 @@ var ts; var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined; var templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), context); - var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode); + var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ undefined); context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } @@ -56853,6 +57029,16 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function forEachPropertyOfType(type, action) { + type = getReducedApparentType(type); + if (type.flags & 3670016 /* StructuredType */) { + resolveStructuredTypeMembers(type).members.forEach(function (symbol, escapedName) { + if (isNamedMember(symbol, escapedName)) { + action(symbol, escapedName); + } + }); + } + } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { var list = obj.properties; return list.some(function (property) { @@ -57789,7 +57975,7 @@ var ts; return false; switch (node.kind) { case 79 /* Identifier */: - return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; case 166 /* PropertyDeclaration */: case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: @@ -59138,6 +59324,8 @@ var ts; // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { includes |= flags & 205258751 /* IncludesMask */; + if (flags & 465829888 /* Instantiable */) + includes |= 33554432 /* IncludesInstantiable */; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { @@ -59246,7 +59434,7 @@ var ts; var _loop_16 = function () { i--; var t = types[i]; - if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) { + if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeMatchedByTemplateLiteralType(t, template); })) { ts.orderedRemoveItemAt(types, i); } }; @@ -59351,7 +59539,7 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + var objectFlags = (includes & 36323363 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | (includes & 2097152 /* Intersection */ ? 33554432 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } @@ -60328,12 +60516,6 @@ var ts; } return type[cache] = type; } - function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { - var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); - var checkType = type.checkType; - var extendsType = type.extendsType; - return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); - } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -60642,6 +60824,10 @@ var ts; } return result; } + function isDistributionDependent(root) { + return root.isDistributive && (isTypeParameterPossiblyReferenced(root.checkType, root.node.trueType) || + isTypeParameterPossiblyReferenced(root.checkType, root.node.falseType)); + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -61441,7 +61627,9 @@ var ts; return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { if (!type.declaration.nameType) { - if (isArrayType(t)) { + var constraint = void 0; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && + (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, ts.or(isArrayType, isTupleType))) { return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); } if (isGenericTupleType(t)) { @@ -62981,13 +63169,12 @@ var ts; traceUnionsOrIntersectionsTooLarge(source, target); var result = 0 /* False */; var saveErrorInfo = captureErrorCalculationState(); - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { - result = getConstituentCount(source) * getConstituentCount(target) >= 4 ? - recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags) : - structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) { + // We skip caching when source or target is a union with no more than three constituents. + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); + } + else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { + result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags); } if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { @@ -63444,19 +63631,19 @@ var ts; var maybeStart = maybeCount; maybeKeys[maybeCount] = id; maybeCount++; + var saveExpandingFlags = expandingFlags; if (recursionFlags & 1 /* Source */) { sourceStack[sourceDepth] = source; sourceDepth++; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) + expandingFlags |= 1 /* Source */; } if (recursionFlags & 2 /* Target */) { targetStack[targetDepth] = target; targetDepth++; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) + expandingFlags |= 2 /* Target */; } - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, sourceDepth)) - expandingFlags |= 1 /* Source */; - if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, targetDepth)) - expandingFlags |= 2 /* Target */; var originalHandler; var propagatingVarianceFlags = 0; if (outofbandVarianceMarkerHandler) { @@ -63480,13 +63667,13 @@ var ts; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } - expandingFlags = saveExpandingFlags; if (recursionFlags & 1 /* Source */) { sourceDepth--; } if (recursionFlags & 2 /* Target */) { targetDepth--; } + expandingFlags = saveExpandingFlags; if (result) { if (result === -1 /* True */ || (sourceDepth === 0 && targetDepth === 0)) { if (result === -1 /* True */ || result === 3 /* Maybe */) { @@ -63727,7 +63914,7 @@ var ts; originalErrorInfo = undefined; } } - else if (isGenericMappedType(target)) { + else if (isGenericMappedType(target) && relation !== identityRelation) { // Check if source type `S` is related to target type `{ [P in Q]: T }` or `{ [P in Q as R]: T}`. var keysRemapped = !!target.declaration.nameType; var templateType = getTemplateTypeFromMappedType(target); @@ -63791,32 +63978,28 @@ var ts; } } else if (target.flags & 16777216 /* Conditional */) { - var c = target; - // Check if the conditional is always true or always false but still deferred for distribution purposes - var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); - var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); - // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, - // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when - // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, - // to which `{x: string | number, y: string | number}` isn't assignable) - var distributionMapper = void 0; - var checkVar = getActualTypeVariable(c.root.checkType); - if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { - var newParam = cloneTypeParameter(checkVar); - distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); - newParam.mapper = distributionMapper; - } - // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) - var expanding = isDeeplyNestedType(target, targetStack, targetDepth); - var localResult = expanding ? 3 /* Maybe */ : undefined; - if (skipTrue || expanding || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false))) { - if (!skipFalse && !expanding) { - localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); - } - } - if (localResult) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { resetErrorInfo(saveErrorInfo); - return localResult; + return 3 /* Maybe */; + } + var c = target; + // We check for a relationship to a conditional type target only when the conditional type has no + // 'infer' positions and is not distributive or is distributive but doesn't reference the check type + // parameter in either of the result types. + if (!c.root.inferTypeParameters && !isDistributionDependent(c.root)) { + // Check if the conditional is always true or always false but still deferred for distribution purposes. + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + if (result = skipTrue ? -1 /* True */ : isRelatedTo(source, getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false)) { + result &= skipFalse ? -1 /* True */ : isRelatedTo(source, getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ false); + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + } } } else if (target.flags & 134217728 /* TemplateLiteral */) { @@ -63828,8 +64011,7 @@ var ts; // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - var result_9 = inferTypesFromTemplateLiteralType(source, target); - if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + if (isTypeMatchedByTemplateLiteralType(source, target)) { return -1 /* True */; } } @@ -63887,33 +64069,34 @@ var ts; } } else if (source.flags & 16777216 /* Conditional */) { + // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive + // conditional type and bail out with a Ternary.Maybe result. + if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { + resetErrorInfo(saveErrorInfo); + return 3 /* Maybe */; + } if (target.flags & 16777216 /* Conditional */) { - // If one of the conditionals under comparison seems to be infinitely expanding, stop comparing it - back out, try - // the constraint, and failing that, give up trying to relate the two. This is the only way we can handle recursive conditional - // types, which might expand forever. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth) && !isDeeplyNestedType(target, targetStack, targetDepth)) { - // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if - // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, - // and Y1 is related to Y2. - var sourceParams = source.root.inferTypeParameters; - var sourceExtends = source.extendsType; - var mapper = void 0; - if (sourceParams) { - // If the source has infer type parameters, we instantiate them in the context of the target - var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); - sourceExtends = instantiateType(sourceExtends, ctx.mapper); - mapper = ctx.mapper; + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + var sourceParams = source.root.inferTypeParameters; + var sourceExtends = source.extendsType; + var mapper = void 0; + if (sourceParams) { + // If the source has infer type parameters, we instantiate them in the context of the target + var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedToWorker); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); + sourceExtends = instantiateType(sourceExtends, ctx.mapper); + mapper = ctx.mapper; + } + if (isTypeIdenticalTo(sourceExtends, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { + if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { + result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); } - if (isTypeIdenticalTo(sourceExtends, target.extendsType) && - (isRelatedTo(source.checkType, target.checkType, 3 /* Both */) || isRelatedTo(target.checkType, source.checkType, 3 /* Both */))) { - if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), 3 /* Both */, reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -63928,17 +64111,13 @@ var ts; } } } - // We'll repeatedly decompose source side conditionals if they're recursive - check if we've already recured on the constraint a lot and, if so, bail - // on the comparison. - if (!isDeeplyNestedType(source, sourceStack, sourceDepth)) { - // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` - // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). - var defaultConstraint = getDefaultConstraintOfConditionalType(source); - if (defaultConstraint) { - if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` + // when `O` is a conditional (`never` is trivially assignable to `O`, as is `O`!). + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, 1 /* Source */, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -64027,9 +64206,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_10) { - return result_10; + var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_9) { + return result_9; } } } @@ -64101,13 +64280,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_11; + var result_10; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { + if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, 3 /* Both */, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); + return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), 3 /* Both */, reportErrors); } } } @@ -65047,14 +65226,15 @@ var ts; // `type A = null extends T ? [A>] : [T]` // has expanded into `[A>>>>>]` // in such cases we need to terminate the expansion, and we do so here. - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5) { + function isDeeplyNestedType(type, stack, depth, maxDepth) { + if (maxDepth === void 0) { maxDepth = 5; } + if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; for (var i = 0; i < depth; i++) { if (getRecursionIdentity(stack[i]) === identity_1) { count++; - if (count >= 5) { + if (count >= maxDepth) { return true; } } @@ -65795,7 +65975,8 @@ var ts; (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) || param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) { var newName = "arg" + param.parent.parameters.indexOf(param); - errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name)); + var typeName = ts.declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); + errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); return; } diagnostic = declaration.dotDotDotToken ? @@ -66189,6 +66370,10 @@ var ts; inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : undefined; } + function isTypeMatchedByTemplateLiteralType(source, target) { + var inferences = inferTypesFromTemplateLiteralType(source, target); + return !!inferences && ts.every(inferences, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); }); + } function getStringLikeTypeForType(type) { return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); } @@ -66965,17 +67150,16 @@ var ts; var inferredType = void 0; var signature = context.signature; if (signature) { - var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; + var inferredCovariantType_1 = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - var inferredContravariantType = getContravariantInference(inference); // If we have both co- and contra-variant inferences, we prefer the contra-variant inference - // unless the co-variant inference is a subtype and not 'never'. - inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) && - isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? - inferredCovariantType : inferredContravariantType; + // unless the co-variant inference is a subtype of some contra-variant inference and not 'never'. + inferredType = inferredCovariantType_1 && !(inferredCovariantType_1.flags & 131072 /* Never */) && + ts.some(inference.contraCandidates, function (t) { return isTypeSubtypeOf(inferredCovariantType_1, t); }) ? + inferredCovariantType_1 : getContravariantInference(inference); } - else if (inferredCovariantType) { - inferredType = inferredCovariantType; + else if (inferredCovariantType_1) { + inferredType = inferredCovariantType_1; } else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -67076,8 +67260,7 @@ var ts; if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), - /*excludeGlobals*/ false, - /*issueSuggestions*/ true) || unknownSymbol; + /*excludeGlobals*/ false) || unknownSymbol; } return links.resolvedSymbol; } @@ -67094,8 +67277,11 @@ var ts; function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 79 /* Identifier */: - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + if (!ts.isThisInTypeQuery(node)) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + } + // falls through case 108 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); case 229 /* NonNullExpression */: @@ -67275,8 +67461,9 @@ var ts; // constituent types keyed by the literal types of the property by that name in each constituent type. function getKeyPropertyName(unionType) { var types = unionType.types; - // We only construct maps for large unions with non-primitive constituents. - if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + // We only construct maps for unions with many non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */ || + ts.countWhere(types, function (t) { return !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */)); }) < 10) { return undefined; } if (unionType.keyPropertyName === undefined) { @@ -67309,7 +67496,7 @@ var ts; var keyPropertyName = getKeyPropertyName(unionType); var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 294 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); - var propType = propNode && getTypeOfExpression(propNode.initializer); + var propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } function isOrContainsMatchingReference(source, target) { @@ -67725,7 +67912,7 @@ var ts; mapType(type, mapper); } function getConstituentCount(type) { - return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; + return type.flags & 1048576 /* Union */ ? type.types.length : 1; } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); @@ -69223,7 +69410,7 @@ var ts; return parent.kind === 205 /* PropertyAccessExpression */ || parent.kind === 207 /* CallExpression */ && parent.expression === node || parent.kind === 206 /* ElementAccessExpression */ && parent.expression === node && - !(isGenericTypeWithoutNullableConstraint(type) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); + !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression))); } function isGenericTypeWithUnionConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); @@ -70544,7 +70731,7 @@ var ts; return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 294 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 284 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return getContextFreeTypeOfExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -71099,6 +71286,10 @@ var ts; function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { + if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) { + return links.resolvedType = errorType; + } links.resolvedType = checkExpression(node.expression); // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. // (It needs to be bound at class evaluation time.) @@ -72568,7 +72759,7 @@ var ts; if (relatedInfo) { ts.addRelatedInfo(resultDiagnostic, relatedInfo); } - addErrorOrSuggestion(!isUncheckedJS, resultDiagnostic); + addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== ts.Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && @@ -72641,7 +72832,19 @@ var ts; // 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 // So the table *contains* `x` but `x` isn't actually in scope. // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. - return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + if (symbol) + return symbol; + var candidates; + if (symbols === globals) { + var primitives = ts.mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], function (s) { return symbols.has((s.charAt(0).toUpperCase() + s.slice(1))) + ? createSymbol(524288 /* TypeAlias */, s) + : undefined; }); + candidates = primitives.concat(ts.arrayFrom(symbols.values())); + } + else { + candidates = ts.arrayFrom(symbols.values()); + } + return getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), candidates, meaning); }); return result; } @@ -74807,11 +75010,33 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } } return createPromiseReturnType(node, anyType); } + function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) { + var memberTable = ts.createSymbolTable(); + var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.parent = originalSymbol; + newSymbol.nameType = getStringLiteralType("default"); + newSymbol.target = resolveSymbol(symbol); + memberTable.set("default" /* Default */, newSymbol); + return createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + } + function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { + var hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier); + if (hasDefaultOnly && type && !isErrorType(type)) { + var synthType = type; + if (!synthType.defaultOnlyType) { + var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_4; + } + return synthType.defaultOnlyType; + } + return undefined; + } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) { var _a; if (allowSyntheticDefaultImports && type && !isErrorType(type)) { @@ -74820,14 +75045,8 @@ var ts; var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false, moduleSpecifier); if (hasSyntheticDefault) { - var memberTable = ts.createSymbolTable(); - var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); - newSymbol.parent = originalSymbol; - newSymbol.nameType = getStringLiteralType("default"); - newSymbol.target = resolveSymbol(symbol); - memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); - var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, ts.emptyArray); + var defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); anonymousSymbol.type = defaultContainingObject; synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; } @@ -75535,12 +75754,12 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_4 = getBaseConstraintOfType(operandType) || operandType; + var type_5 = getBaseConstraintOfType(operandType) || operandType; // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_4.flags & 3 /* AnyOrUnknown */) { + if (type_5.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */; } - return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -78130,7 +78349,9 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + if (!typeParameters) + return undefined; var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -78141,7 +78362,7 @@ var ts; ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); + checkIndexConstraints(type, type.symbol); checkTypeForDuplicateIndexSignatures(node); checkObjectTypeForDuplicateDeclarations(node); } @@ -78236,6 +78457,7 @@ var ts; checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } function checkMappedType(node) { + checkGrammarMappedType(node); checkSourceElement(node.typeParameter); checkSourceElement(node.nameType); checkSourceElement(node.type); @@ -78252,6 +78474,12 @@ var ts; checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter)); } } + function checkGrammarMappedType(node) { + var _a; + if ((_a = node.members) === null || _a === void 0 ? void 0 : _a.length) { + return grammarErrorOnNode(node.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } + } function checkThisType(node) { getTypeFromThisTypeNode(node); } @@ -78629,12 +78857,12 @@ var ts; case 264 /* ImportEqualsDeclaration */: case 267 /* NamespaceImport */: case 266 /* ImportClause */: - var result_12 = 0 /* None */; + var result_11 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { - result_12 |= getDeclarationSpaces(d); + result_11 |= getDeclarationSpaces(d); }); - return result_12; + return result_11; case 253 /* VariableDeclaration */: case 202 /* BindingElement */: case 255 /* FunctionDeclaration */: @@ -81197,7 +81425,7 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type, isStaticIndex) { + function checkIndexConstraints(type, symbol, isStaticIndex) { var indexInfos = getIndexInfosOfType(type); if (indexInfos.length === 0) { return; @@ -81208,15 +81436,15 @@ var ts; checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */, /*includeNonPublic*/ true), getNonMissingTypeOfSymbol(prop)); } } - var typeDeclaration = type.symbol.valueDeclaration; + var typeDeclaration = symbol.valueDeclaration; if (typeDeclaration && ts.isClassLike(typeDeclaration)) { for (var _b = 0, _c = typeDeclaration.members; _b < _c.length; _b++) { var member = _c[_b]; // Only process instance properties with computed names here. Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. if (!ts.isStatic(member) && !hasBindableName(member)) { - var symbol = getSymbolOfNode(member); - checkIndexConstraintForProperty(type, symbol, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol)); + var symbol_3 = getSymbolOfNode(member); + checkIndexConstraintForProperty(type, symbol_3, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol_3)); } } } @@ -81503,7 +81731,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); + checkMembersForOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -81532,14 +81760,13 @@ var ts; } } if (produceDiagnostics) { - checkIndexConstraints(type); - checkIndexConstraints(staticType, /*isStaticIndex*/ true); + checkIndexConstraints(type, symbol); + checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } - function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { - var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) { var baseTypeNode = ts.getEffectiveBaseTypeNode(node); var baseTypes = baseTypeNode && getBaseTypes(type); var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; @@ -81551,46 +81778,71 @@ var ts; if (ts.isConstructorDeclaration(member)) { ts.forEach(member.parameters, function (param) { if (ts.isParameterPropertyDeclaration(param, member)) { - checkClassMember(param, /*memberIsParameterProperty*/ true); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, + /* memberIsParameterProperty */ true); } }); } - checkClassMember(member); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, + /* memberIsParameterProperty */ false); }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; _loop_29(member); } - function checkClassMember(member, memberIsParameterProperty) { - var hasOverride = ts.hasOverrideModifier(member); - var hasStatic = ts.isStatic(member); - var isJs = ts.isInJSFile(member); - if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { - var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); - if (!declaredProp) { - return; - } - var thisType = hasStatic ? staticType : typeWithThis; - var baseType = hasStatic ? baseStaticType : baseWithThis; - var prop = getPropertyOfType(thisType, declaredProp.escapedName); - var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); - var baseClassName = typeToString(baseWithThis); - if (prop && !baseProp && hasOverride) { - var suggestion = getSuggestedSymbolForNonexistentClassMember(ts.symbolName(declaredProp), baseType); + } + /** + * @param member Existing member node to be checked. + * Note: `member` cannot be a synthetic node. + */ + function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { + if (reportErrors === void 0) { reportErrors = true; } + var declaredProp = member.name + && getSymbolAtLocation(member.name) + || getSymbolAtLocation(member); + if (!declaredProp) { + return 0 /* Ok */; + } + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, ts.hasOverrideModifier(member), ts.hasAbstractModifier(member), ts.isStatic(member), memberIsParameterProperty, ts.symbolName(declaredProp), reportErrors ? member : undefined); + } + /** + * Checks a class member declaration for either a missing or an invalid `override` modifier. + * Note: this function can be used for speculative checking, + * i.e. checking a member that does not yet exist in the program. + * An example of that would be to call this function in a completions scenario, + * when offering a method declaration as completion. + * @param errorNode The node where we should report an error, or undefined if we should not report errors. + */ + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { + var isJs = ts.isInJSFile(node); + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { + var memberEscapedName = ts.escapeLeadingUnderscores(memberName); + var thisType = memberIsStatic ? staticType : typeWithThis; + var baseType = memberIsStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, memberEscapedName); + var baseProp = getPropertyOfType(baseType, memberEscapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && memberHasOverrideModifier) { + if (errorNode) { + var suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); // Again, using symbol name: note that's different from `symbol.escapedName` suggestion ? - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } - else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { - var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); - if (hasOverride) { - return; - } - if (!baseHasAbstract) { + return 2 /* HasInvalidOverride */; + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.some(baseProp.declarations, ts.hasAbstractModifier); + if (memberHasOverrideModifier) { + return 0 /* Ok */; + } + if (!baseHasAbstract) { + if (errorNode) { var diag = memberIsParameterProperty ? isJs ? ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : @@ -81598,20 +81850,28 @@ var ts; isJs ? ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; - error(member, diag, baseClassName); + error(errorNode, diag, baseClassName); } - else if (ts.hasAbstractModifier(member) && baseHasAbstract) { - error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + return 1 /* NeedsOverride */; + } + else if (memberHasAbstractModifier && baseHasAbstract) { + if (errorNode) { + error(errorNode, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); } + return 1 /* NeedsOverride */; } } - else if (hasOverride) { + } + else if (memberHasOverrideModifier) { + if (errorNode) { var className = typeToString(type); - error(member, isJs ? + error(errorNode, isJs ? ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } + return 2 /* HasInvalidOverride */; } + return 0 /* Ok */; } 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 @@ -81654,6 +81914,31 @@ var ts; } } } + /** + * Checks a member declaration node to see if has a missing or invalid `override` modifier. + * @param node Class-like node where the member is declared. + * @param member Member declaration node. + * Note: `member` can be a synthetic node without a parent. + */ + function getMemberOverrideModifierStatus(node, member) { + if (!member.name) { + return 0 /* Ok */; + } + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var memberHasOverrideModifier = member.parent + ? ts.hasOverrideModifier(member) + : ts.hasSyntacticModifier(member, 16384 /* Override */); + var memberName = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(member.name)); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, ts.hasAbstractModifier(member), ts.isStatic(member), + /* memberIsParameterProperty */ false, memberName); + } function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -81924,7 +82209,7 @@ var ts; var baseType = _a[_i]; checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); } - checkIndexConstraints(type); + checkIndexConstraints(type, symbol); } } checkObjectTypeForDuplicateDeclarations(node); @@ -86115,6 +86400,9 @@ var ts; } } function checkGrammarProperty(node) { + if (ts.isComputedPropertyName(node.name) && ts.isBinaryExpression(node.name.expression) && node.name.expression.operatorToken.kind === 101 /* InKeyword */) { + return grammarErrorOnNode(node.parent.members[0], ts.Diagnostics.A_mapped_type_may_not_declare_properties_or_methods); + } if (ts.isClassLike(node.parent)) { if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); @@ -86134,7 +86422,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 181 /* TypeLiteral */) { + else if (ts.isTypeLiteralNode(node.parent)) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -86811,7 +87099,7 @@ var ts; return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); case 194 /* MappedType */: ts.Debug.type(node); - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 195 /* LiteralType */: ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); @@ -94647,11 +94935,11 @@ var ts; currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } - function getJsxFactoryCalleePrimitive(childrenLength) { - return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx"; + function getJsxFactoryCalleePrimitive(isStaticChildren) { + return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx"; } - function getJsxFactoryCallee(childrenLength) { - var type = getJsxFactoryCalleePrimitive(childrenLength); + function getJsxFactoryCallee(isStaticChildren) { + var type = getJsxFactoryCalleePrimitive(isStaticChildren); return getImplicitImportForName(type); } function getImplicitJsxFragmentReference() { @@ -94798,60 +95086,37 @@ var ts; return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node); } function convertJsxChildrenToChildrenPropObject(children) { + var prop = convertJsxChildrenToChildrenPropAssignment(children); + return prop && factory.createObjectLiteralExpression([prop]); + } + function convertJsxChildrenToChildrenPropAssignment(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); - if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) - ]); + if (ts.length(nonWhitespaceChildren) === 1 && !nonWhitespaceChildren[0].dotDotDotToken) { + var result_12 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_12 && factory.createPropertyAssignment("children", result_12); } var result = ts.mapDefined(children, transformJsxChildToExpression); - return !result.length ? undefined : factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) - ]); + return ts.length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined; } function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; + var childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined; var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; }); var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties; - var segments = []; - if (attrs.length) { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - } - if (children && children.length) { - var result = convertJsxChildrenToChildrenPropObject(children); - if (result) { - segments.push(result); - } - } - if (segments.length === 0) { - objectProperties = factory.createObjectLiteralExpression([]); - // When there are no attributes, React wants {} - } - else { - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments); - } - return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location); + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : + factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : ts.emptyArray); // When there are no attributes, React wants {} + return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || ts.emptyArray, isChild, location); } - function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) { + function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { + var _a; + var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); + var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; if (compilerOptions.jsx === 5 /* ReactJSXDev */) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { // isStaticChildren development flag - args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse()); + args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); // __source development flag var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos); args.push(factory.createObjectLiteralExpression([ @@ -94863,7 +95128,7 @@ var ts; args.push(factory.createThis()); } } - var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location); + var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args), location); if (isChild) { ts.startOnNewLine(element); } @@ -94871,38 +95136,9 @@ var ts; } function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) { var tagName = getTagName(node); - var objectProperties; var attrs = node.attributes.properties; - if (attrs.length === 0) { - objectProperties = factory.createNull(); - // When there are no attributes, React wants "null" - } - else { - var target = ts.getEmitScriptTarget(compilerOptions); - if (target && target >= 5 /* ES2018 */) { - objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { - return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); - }))); - } - else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); - } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); - } - } - } + var objectProperties = ts.length(attrs) ? transformJsxAttributesToObjectProps(attrs) : + factory.createNull(); // When there are no attributes, React wants "null" var callee = currentFileState.importSpecifier === undefined ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 node) @@ -94922,7 +95158,7 @@ var ts; } } return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), - /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location); + /*keyAttr*/ undefined, children, isChild, location); } function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 @@ -94935,6 +95171,36 @@ var ts; function transformJsxSpreadAttributeToSpreadAssignment(node) { return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); } + function transformJsxAttributesToObjectProps(attrs, children) { + var target = ts.getEmitScriptTarget(compilerOptions); + return target && target >= 5 /* ES2018 */ ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : + transformJsxAttributesToExpression(attrs, children); + } + function transformJsxAttributesToProps(attrs, children) { + var props = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return ts.map(attrs, function (attr) { return isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr) : transformJsxAttributeToObjectLiteralElement(attr); }); + })); + if (children) { + props.push(children); + } + return props; + } + function transformJsxAttributesToExpression(attrs, children) { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var expressions = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + expressions.unshift(factory.createObjectLiteralExpression()); + } + if (children) { + expressions.push(factory.createObjectLiteralExpression([children])); + } + return ts.singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -98350,78 +98616,17 @@ var ts; * @param node A TemplateExpression node. */ function visitTemplateExpression(node) { - var expressions = []; - addTemplateHead(expressions, node); - addTemplateSpans(expressions, node); - // createAdd will check if each expression binds less closely than binary '+'. - // If it does, it wraps the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var expression = ts.reduceLeft(expressions, factory.createAdd); - if (ts.nodeIsSynthesized(expression)) { - ts.setTextRange(expression, node); - } - return expression; - } - /** - * Gets a value indicating whether we need to include the head of a TemplateExpression. - * - * @param node A TemplateExpression node. - */ - function shouldAddTemplateHead(node) { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - /** - * Adds the head of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateHead(expressions, node) { - if (!shouldAddTemplateHead(node)) { - return; - } - expressions.push(factory.createStringLiteral(node.head.text)); - } - /** - * Visits and adds the template spans of a TemplateExpression to an array of expressions. - * - * @param expressions An array of expressions. - * @param node A TemplateExpression node. - */ - function addTemplateSpans(expressions, node) { + var expression = factory.createStringLiteral(node.head.text); for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { var span = _a[_i]; - expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span.literal.text.length !== 0) { - expressions.push(factory.createStringLiteral(span.literal.text)); + var args = [ts.visitNode(span.expression, visitor, ts.isExpression)]; + if (span.literal.text.length > 0) { + args.push(factory.createStringLiteral(span.literal.text)); } + expression = factory.createCallExpression(factory.createPropertyAccessExpression(expression, "concat"), + /*typeArguments*/ undefined, args); } + return ts.setTextRange(expression, node); } /** * Visits the `super` keyword @@ -108041,7 +108246,14 @@ var ts; // clear the parenthesizer rule as we ascend currentParenthesizerRule = undefined; } - function pipelineEmitWithHintWorker(hint, node) { + function pipelineEmitWithHintWorker(hint, node, allowSnippets) { + if (allowSnippets === void 0) { allowSnippets = true; } + if (allowSnippets) { + var snippet = ts.getSnippetElement(node); + if (snippet) { + return emitSnippetNode(hint, node, snippet); + } + } if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -108650,6 +108862,28 @@ var ts; } } // + // Snippet Elements + // + function emitSnippetNode(hint, node, snippet) { + switch (snippet.kind) { + case 1 /* Placeholder */: + emitPlaceholder(hint, node, snippet); + break; + case 0 /* TabStop */: + emitTabStop(snippet); + break; + } + } + function emitPlaceholder(hint, node, snippet) { + nonEscapingWrite("${" + snippet.order + ":"); // `${2:` + pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...` + nonEscapingWrite("}"); // `}` + // `${2:...}` + } + function emitTabStop(snippet) { + nonEscapingWrite("$" + snippet.order); + } + // // Identifiers // function emitIdentifier(node) { @@ -110888,6 +111122,15 @@ var ts; function writeProperty(s) { writer.writeProperty(s); } + function nonEscapingWrite(s) { + // This should be defined in a snippet-escaping text writer. + if (writer.nonEscapingWrite) { + writer.nonEscapingWrite(s); + } + else { + writer.write(s); + } + } function writeLine(count) { if (count === void 0) { count = 1; } for (var i = 0; i < count; i++) { @@ -112157,7 +112400,7 @@ var ts; var rootResult = tryReadDirectory(rootDir, rootDirPath); var rootSymLinkResult; if (rootResult !== undefined) { - return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath, directoryExists); + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -113129,7 +113372,7 @@ var ts; break; case ts.FileIncludeKind.TypeReferenceDirective: (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end); - packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), getModeForResolutionAtIndex(file, index))) === null || _g === void 0 ? void 0 : _g.packageId; + packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), file.impliedNodeFormat)) === null || _g === void 0 ? void 0 : _g.packageId; break; case ts.FileIncludeKind.LibReferenceDirective: (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end); @@ -113691,15 +113934,15 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_13 = []; var i = 0; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i)); i++; - result_14.push(resolvedModule); + result_13.push(resolvedModule); } - return result_14; + return result_13; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -113991,8 +114234,8 @@ var ts; var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); }); var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile); // ensure that types resolutions are still correct - var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); - if (typeReferenceEesolutionsChanged) { + var typeReferenceResolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, ts.typeDirectiveIsEqualTo); + if (typeReferenceResolutionsChanged) { structureIsReused = 1 /* SafeModules */; newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions); } @@ -115280,6 +115523,21 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { + var isNightly = ts.stringContains(ts.version, "-dev"); + if (!isNightly) { + if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); + } + else if (ts.getEmitModuleKind(options) === ts.ModuleKind.NodeNext) { + createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "nodenext"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "node12"); + } + else if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + createOptionValueDiagnostic("moduleResolution", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "moduleResolution", "nodenext"); + } + } if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } @@ -115428,7 +115686,9 @@ var ts; } } if (options.resolveJsonModule) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Node12 && + ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeNext) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } // Any emit other than common js, amd, es2015 or esnext is error @@ -115756,8 +116016,8 @@ var ts; function createDiagnosticForOptionName(message, option1, option2, option3) { createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + function createOptionValueDiagnostic(option1, message, arg0, arg1) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1); } function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) { var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; }); @@ -118001,6 +118261,9 @@ var ts; else { resolution = loader(name, containingFile, compilerOptions, ((_c = resolutionHost.getCompilerHost) === null || _c === void 0 ? void 0 : _c.call(resolutionHost)) || resolutionHost, redirectedReference, containingSourceFile); perDirectoryResolution.set(name, mode, resolution); + if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { + resolutionHost.onDiscoveredSymlink(); + } } resolutionsInFile.set(name, mode, resolution); watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); @@ -118469,6 +118732,11 @@ var ts; } } ts.createResolutionCache = createResolutionCache; + function resolutionIsSymlink(resolution) { + var _a, _b; + return !!(((_a = resolution.resolvedModule) === null || _a === void 0 ? void 0 : _a.originalPath) || + ((_b = resolution.resolvedTypeReferenceDirective) === null || _b === void 0 ? void 0 : _b.originalPath)); + } })(ts || (ts = {})); // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. /* @internal */ @@ -118761,9 +119029,9 @@ var ts; if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_14 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_14) + return result_14; } var symlinkedDirectories = (_a = host.getSymlinkCache) === null || _a === void 0 ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); @@ -118783,10 +119051,10 @@ var ts; for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { var symlinkDirectory = symlinkDirectories_1[_i]; var option = ts.resolvePath(symlinkDirectory, relative); - var result_16 = cb(option, target === referenceRedirect); + var result_15 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths - if (result_16) - return result_16; + if (result_15) + return result_15; } }); }); @@ -119079,13 +119347,15 @@ var ts; if (host.fileExists(packageJsonPath)) { var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); // TODO: Inject `require` or `import` condition based on the intended import mode - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; - if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; - return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); - } - if (packageJsonContent.exports) { - return { moduleFileToTry: path, blockedByExports: true }; + if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + if (fromExports) { + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); + } + if (packageJsonContent.exports) { + return { moduleFileToTry: path, blockedByExports: true }; + } } var versionPaths = packageJsonContent.typesVersions ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -120127,6 +120397,9 @@ var ts; sourceFilesCache.set(path, false); } } + if (sourceFile) { + sourceFile.impliedNodeFormat = ts.getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings()); + } return sourceFile; } return hostSourceFile.sourceFile; @@ -121083,11 +121356,11 @@ var ts; (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { - var path = _a[0], data = _a[1]; - return [state.host.realpath ? toPath(state, state.host.realpath(path)) : path, data]; - })); if (state.watch) { + state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && ts.map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), function (_a) { + var path = _a[0], data = _a[1]; + return [state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data]; + })); state.builderPrograms.set(projectPath, program); } step++; diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 6beae8abf1502..d07d223c6da6d 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "此处不允许使用 'A 标签。", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "标记的元组元素被声明为可选,并且问号位于名称之后、冒号之前,而不是位于类型之后。", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "标记的元组元素通过在名称之前(而不是类型之前)的 “...” 声明为 rest。", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "映射的类型可能不声明属性或方法。", "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 类必须具有单个 rest 参数为类型 \"any[]\" 的构造函数。", "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "从包含抽象构造签名的类型变量扩展的 mixin 类也必须声明为 \"abstract\"。", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "找不到名称 \"{0}\"。是否需要为节点安装类型定义? 请尝试使用 `npm i --save-dev @types/node`。", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "找不到名称“{0}”。是否需要为节点安装类型定义? 请尝试使用 `npm i --save-dev @types/node`,然后将 “node” 添加到类型字段。", "Cannot_find_namespace_0_2503": "找不到命名空间“{0}”。", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "找不到命名空间“{0}”。你是否指的是“{1}”?", "Cannot_find_parameter_0_1225": "找不到参数“{0}”。", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到输入文件的公共子目录路径。", "Cannot_find_type_definition_file_for_0_2688": "找不到“{0}”的类型定义文件。", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "将重载列表转换为单一签名", "Convert_parameters_to_destructured_object_95075": "将参数转换为析构对象", "Convert_require_to_import_95047": "将 \"require\" 转换为 \"import\"", - "Convert_to_ES6_module_95017": "转换为 ES6 模块", + "Convert_to_ES_module_95017": "转换为 ES 模块", "Convert_to_a_bigint_numeric_literal_95091": "转换为 bigint 数字文本", "Convert_to_anonymous_function_95123": "转换为异步函数", "Convert_to_arrow_function_95125": "转换为箭头函数", @@ -561,7 +563,7 @@ "Duplicate_property_0_2718": "重复的属性 \"{0}\"。", "Dynamic_import_cannot_have_type_arguments_1326": "动态导入不能含有类型参数。", "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "动态导入的说明符类型必须是 \"string\",但此处类型是 \"{0}\"。", - "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323": "仅当 '--module' 标志设置为 'es2020'、'esnext'、 'commonjs'、'amd'、'system'、'umd'、'node12' 或 'nodenext' 时,才支持动态导入。", + "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323": "仅当 '--module' 标志设置为 'es2020'、'es2022'、'esnext'、 'commonjs'、'amd'、'system'、'umd'、'node12' 或 'nodenext' 时,才支持动态导入。", "Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments_1450": "动态导入只能接受模块说明符和可选断言作为参数", "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324": "只有在 \"--module\" 选项设置为 \"esnext\" 时,动态导入才支持第二个参数。", "Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_2762": "联合类型 \"{0}\" 的每个成员都有构造签名,但这些签名都不能互相兼容。", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "找不到文件“{0}”。", "File_Management_6245": "文件管理", "File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "文件是 CommonJS 模块;它可能会转换为 ES6 模块。", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "文件是 CommonJS 模块; 它可能会转换为 ES 模块。", "File_is_default_library_for_target_specified_here_1426": "文件是此处指定的目标的默认库。", "File_is_entry_point_of_type_library_specified_here_1419": "文件是此处指定的类型库的入口点。", "File_is_included_via_import_here_1399": "在此处通过导入包含了文件。", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc \"@typedef\" 标记应具有类型注释,或其后跟有 \"@property\" 或 \"@member\" 标记。", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 类型只能在文档注释内部使用。", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 类型可能会移到 TypeScript 类型。", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "JSON 导入在 ES 模块模式导入中是实验性的。", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "只能为 JSX 属性分配非空“表达式”。", "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 元素“{0}”没有相应的结束标记。", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "JSX 元素类不支持特性,因为它不具有“{0}”属性。", @@ -1360,7 +1363,7 @@ "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全局类型 \"JSX.{0}\" 不可具有多个属性。", "The_implementation_signature_is_declared_here_2750": "在此处声明实现签名。", "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470": "将生成到 CommonJS 输出的文件中不允许 'import.meta' 元属性。", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_system_node12__1343": "仅当 '--module' 选项为 'es2020'、'esnext'、 'system'、'node12' 或 'nodenext' 时,才允许 'import.meta' 元属性。", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system__1343": "仅当 '--module' 选项为 'es2020'、'es2022'、'esnext'、 'system'、'node12' 或 'nodenext' 时,才允许 'import.meta' 元属性。", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "如果没有引用 \"{1}\",则无法命名 \"{0}\" 的推断类型。这很可能不可移植。需要类型注释。", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "推断类型“{0}”引用的类型具有无法简单序列化的循环结构。必须具有类型注释。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。", @@ -1459,9 +1462,9 @@ "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "此语法需要一个导入的帮助程序,但找不到模块“{0}”。", "This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_ve_2343": "此语法需要名为 \"{1}\" 的导入帮助器,\"{0}\" 中不存在该帮助器。请考虑升级 \"{0}\" 的版本。", "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807": "此语法需要一个名为 \"{1}\" 且包含 {2} 参数的导入帮助程序,该帮助程序与 \"{0}\" 中的相应帮助程序不兼容。请考虑升级 \"{0}\" 的版本。", - "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_noden_1378": "仅当 'module' 选项设置为 'esnext'、'system' 或 'nodenext',且 'target' 选项设置为 'es2017' 或更高版本时,才允许顶级 'await' 表达式。", + "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_o_1378": "仅当 'module' 选项设置为 'es2022'、'esnext'、'system' 或 'nodenext',且 'target' 选项设置为 'es2017' 或更高版本时,才允许顶级 'await' 表达式。", "Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier_1046": ".d.ts 文件中的顶级声明必须以 \"declare\" 或 \"export\" 修饰符开头。", - "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_system_or_nodenex_1432": "仅当 'module' 选项设置为 'esnext'、'system' 或 'nodenext',且 'target' 选项设置为 'es2017' 或更高版本时,才允许顶级 'for await' 循环。", + "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or__1432": "仅当 'module' 选项设置为 'es2022'、'esnext'、'system' 或 'nodenext',且 'target' 选项设置为 'es2017' 或更高版本时,才允许顶级 'for await' 循环。", "Trailing_comma_not_allowed_1009": "不允许使用尾随逗号。", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "将每个文件转换为单独的模块(类似 \"ts.transpileModule\")。", "Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035": "尝试使用 `npm i --save-dev @types/{1}` (如果存在),或者添加一个包含 `declare module '{0}';` 的新声明(.d.ts)文件", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "\"{0}\" 在类 \"{1}\" 中定义为访问器,但这里在 \"{2}\" 中重写为实例属性。", "_0_is_deprecated_6385": "“{0}”已弃用。", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "“{0}”不是关键字“{1}”的有效元属性。是否是指“{2}”?", + "_0_is_not_allowed_as_a_parameter_name_1390": "不允许将 '{0}' 作为参数名。", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "“{0}”不得用作变量声明名称。", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "“{0}”在其自身的基表达式中得到直接或间接引用。", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "“{0}”在其自身的类型批注中得到直接或间接引用。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index a35ca852d9f33..857ddb696d155 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -47,6 +47,7 @@ "A_label_is_not_allowed_here_1344": "此處不允許標籤。", "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086": "標記的元組元素已宣告為選用,並在名稱之後、冒號之前加上問號,而非加在類型之後。", "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087": "標記的元組元素已宣告為待用,並在名稱之前加上「...」,而非加在類型之前。", + "A_mapped_type_may_not_declare_properties_or_methods_7061": "對應型別不能宣告屬性或方法。", "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_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797": "從包含抽象建構簽章之類型變數所延伸的 mixin 類別也必須宣告為 'abstract'。", @@ -322,6 +323,7 @@ "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580": "找不到名稱 '{0}'。需要安裝節點的型別定義嗎? 請嘗試 `npm i --save-dev @types/node`。", "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591": "找不到名稱「{0}」。需要為節點安裝類型定義嗎? 請嘗試 `npm i --save-dev @types/node`,然後將 `node` 新增至 tsconfig 中的類型欄位。", "Cannot_find_namespace_0_2503": "找不到命名空間 '{0}'。", + "Cannot_find_namespace_0_Did_you_mean_1_2833": "找不到命名空間 '{0}'。您是不是指 '{1}'?", "Cannot_find_parameter_0_1225": "找不到參數 '{0}'。", "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到輸入檔的一般子目錄路徑。", "Cannot_find_type_definition_file_for_0_2688": "找不到 '{0}' 的類型定義檔案。", @@ -436,7 +438,7 @@ "Convert_overload_list_to_single_signature_95118": "將多載清單轉換成單一特徵標記", "Convert_parameters_to_destructured_object_95075": "將參數轉換為解構的物件", "Convert_require_to_import_95047": "將 'require' 轉換至 'import'", - "Convert_to_ES6_module_95017": "轉換為 ES6 模組", + "Convert_to_ES_module_95017": "轉換為 ES 模組", "Convert_to_a_bigint_numeric_literal_95091": "轉換為 Bigint 數字常值", "Convert_to_anonymous_function_95123": "轉換為匿名函式", "Convert_to_arrow_function_95125": "轉換為箭頭函式", @@ -680,7 +682,7 @@ "File_0_not_found_6053": "找不到檔案 '{0}'。", "File_Management_6245": "檔案管理", "File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...", - "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001": "檔案為 CommonJS 模組; 其可轉換為 ES6 模組。", + "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "檔案為 CommonJS 模組; 其可轉換為 ES 模組。", "File_is_default_library_for_target_specified_here_1426": "檔案是此處指定目標的預設程式庫。", "File_is_entry_point_of_type_library_specified_here_1419": "檔案是此處指定型別程式庫的進入點。", "File_is_included_via_import_here_1399": "檔案透過匯入加入此處。", @@ -837,6 +839,7 @@ "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021": "JSDoc '@typedef' 標記應具有類型註解,或者其後接著 '@property' 或 '@member' 標記。", "JSDoc_types_can_only_be_used_inside_documentation_comments_8020": "JSDoc 類型只能在文件註解中使用。", "JSDoc_types_may_be_moved_to_TypeScript_types_80004": "JSDoc 類型可移為 TypeScript 類型。", + "JSON_imports_are_experimental_in_ES_module_mode_imports_7062": "JSON 匯入在 ES 模組模式匯入中為實驗性。", "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000": "只能將非空白的 'expression' 指派給 JSX 屬性。", "JSX_element_0_has_no_corresponding_closing_tag_17008": "JSX 元素 '{0}' 沒有對應的結尾標記。", "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607": "因為 JSX 項目類別沒有 '{0}' 屬性 (property),所以不支援屬性 (attribute)。", @@ -1659,6 +1662,7 @@ "_0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property_2610": "'{0}' 在類別 '{1}' 中定義為存取子,但在此處的 '{2}' 中卻覆寫為執行個體屬性。", "_0_is_deprecated_6385": "'{0}' 已淘汰。", "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012": "'{0}' 對關鍵字 '{1}' 而言不是有效的中繼屬性。您是指 '{2}' 嗎?", + "_0_is_not_allowed_as_a_parameter_name_1390": "不允許 '{0}' 做為參數名稱。", "_0_is_not_allowed_as_a_variable_declaration_name_1389": "'{0}' 不能是變數宣告名稱。", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' 在其本身的基底運算式中直接或間接受到參考。", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' 在其本身的類型註釋中直接或間接受到參考。", diff --git a/package.json b/package.json index 7cfc23e493505..e8e2b5917f1d1 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", - "version": "4.5.1-rc", + "version": "4.5.2", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index 1d5ce7c59feff..55fd254725f7c 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -5,7 +5,7 @@ namespace ts { // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - export const version = `${versionMajorMinor}.1-rc`; + export const version = "4.5.2" as string; /** * Type of objects whose values are all of the same type.